问题
I need to write a function, is_prime()
, which takes in an integer n > 1 and returns TRUE
if the number is a prime number and False
otherwise. But when I input 2, it always returns False
. Is there anyway to correct this?
def is_prime(x):
if(x > 1):
for i in range(2,x+1):
if( x % i == 0):
return False
else:
return True
else:
return False
回答1:
Two issues:
First issue is that range includes the number itself, which means that it will always return true (for numbers > 1) because prime numbers can divide themselves...
Fix: change range(2,x+1)
to: range(2, x)
Second issue, the first else
should be aligned with the for
(we return true only after trying all the numbers and making sure that none of them divides x
)
Fixed code:
def is_prime(x):
if x > 1:
for i in range(2,x):
if x % i == 0:
return False
else:
return True
else:
return False
回答2:
Instead of doing this, you can also use SymPy module
import sympy
sympy.isprime(5)
Result :
True
回答3:
Although @alfasin's solution is correct (+1), I find the use of else
makes it slightly more challenging to understand.
The else
on the for
loop in particular required me to reread the Python documentation as most sources say that the else
means no break but it really means completed normally, which is true in the case of a loop that didn't run at all!
Here's my rework removing the else
statements which aren't strictly needed:
def is_prime(x):
if x > 1:
for i in range(2, x):
if x % i == 0:
return False
return True
return False
As others will point out, this is probably as inefficient a prime test as you can write. But it works.
来源:https://stackoverflow.com/questions/45892051/finding-prime-numbers-in-python