Finding Prime Numbers In Python
Solution 1:
Solution 2:
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:
defis_prime(x):
if x > 1:
for i inrange(2,x):
if x % i == 0:
returnFalseelse:
returnTrueelse:
returnFalseSolution 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:
defis_prime(x):
if x > 1:
for i inrange(2, x):
if x % i == 0:
returnFalsereturnTruereturnFalseAs others will point out, this is probably as inefficient a prime test as you can write. But it works.
Post a Comment for "Finding Prime Numbers In Python"