I have just made what seems to me to be the first reliable prime-checking program that works. However, I am not sure if it is completely reliable, or if there are problems. It relies on list-making more than math, and it can be slow for bigger numbers. Do you think there are any problems?
def primeChecker(x): if x <= 1 or isinstance(x,float) == True: return str(x) + " is not prime" else: div = ["tepi"] #tepi denotes test element please ignore for i in range(1,x+1,1): if x % i == 0: div.append("d") #d denotes divisible else: div.append("n") #n denotes not divisible if div == "d" and div[x] == "d" and div.count("n") == x - 2: return str(x) + " is prime" else: return str(x) + " is not prime" def primeCheckList(d,e): for i in range(d,e + 1): print primeChecker(i)
Here are some of the tools I used in
primeChecker() to see if it was working right.
print div #these are testing tools print range(1,x+1,1) print div print div[x] print div[2:x] print div.count("n") print x - 2
edit: Barry's feedback
OK, based on what Barry told me, i was able to clean up and otherwise format my code to be more concise, no more lists needed. it seems to run smoother, and is otherwise easier to read. here it is:
def isPrime(x): if x <= 1 or isinstance(x,float): return False else: for divisor in range(2,x,1): if x % divisor == 0: return False return True def primeChecker(n): if isPrime(n): return "%d is prime" % n else: return "%d is not prime" % n def primeCheckList(d,e): for i in range(d,e + 1): print primeChecker(i)
any more feedback to give?