I wrote a function to calculate whether or not a number is prime, but try as it might, it just seems unable to give the correct response. It also prints the n value that is being incremented. Here is the code for the function (in Python, by the way):
def isPrime(x):
for n in range(1, x):
print n
if x % n == 0:
return False
return True
If I input
isPrime(17)
the function returns
1
False
What is going wrong here?
Every number is divisible by 1 and itself. A prime number is a natural number that has no positive divisors other than 1 and itself. Therefore, if you start your for-loop with 1, every number
xwill pass the conditionx % 1 == 0in the first iteration, returningFalse.To fix it, you need to start your loop with 2 instead of 1. Also, as a side-note, you just need to loop from 2 to
sqrt(x), since if there exists a numberq > sqrt(x)that dividesx, then there must also be a numberp = x / qwhich also dividesx, andp < sqrt(x).