Reputation: 3
#!/usr/local/bin/python3.6
def isPrime(n):
if n == 1:
print("1 is a special")
return False
for x in range(2, n):
if n % x == 0:
print("{} is equal to {} * {}".format(n, x, n // x))
return False
else:
print(n, " is a prime number")
return True
for n in range(1, 21):
isPrime(n)
isPrime(2)
isPrime(21)
isPrime(25)
and the result it gives to me is:
1 is a special
3 is a prime number
4 is equal to 2 * 2
5 is a prime number
6 is equal to 2 * 3
7 is a prime number
8 is equal to 2 * 4
9 is a prime number
10 is equal to 2 * 5
11 is a prime number
12 is equal to 2 * 6
13 is a prime number
14 is equal to 2 * 7
15 is a prime number
16 is equal to 2 * 8
17 is a prime number
18 is equal to 2 * 9
19 is a prime number
20 is equal to 2 * 10
21 is a prime number
25 is a prime number
there is no result of (2), and also this is result of 'even-odd' numbers, not 'isPrime' , because in the code 'for x in range(2, n)' , it has calculated only with number 2 for x
what is wrong in my code ?
Upvotes: 0
Views: 75
Reputation: 1207
for x in range(2, n):
if n % x == 0:
print("{} is equal to {} * {}".format(n, x, n // x))
return False
else:
print(n, " is a prime number")
return True
Watch the indentation: else is now is in aligned with for (not with if), and it should solve your problem. Else means that the x got iterated over n, so n%x was never 0 => you got a prime
Upvotes: 0
Reputation: 1082
Do this:
def isPrime(n):
if n == 1:
print("1 is a special")
return False
for x in range(2, n):
if n % x == 0:
print("{} is equal to {} * {}".format(n, x, n // x))
return False
print(n, " is a prime number")
return True
for n in range(1, 21):
isPrime(n)
Upvotes: 0
Reputation: 73470
Don't return True
form the first iteration. Not being divisible by 2 does not make it prime:
for x in range(2, n): # it would be enough to loop to sqrt(n)
if n % x == 0:
# you know it is NOT prime after first divisor found
return False
# you only know it IS prime after you tried all possible divisors
return True
Upvotes: 1