Python Calculating Prime Numbers
I have to define a function called is_prime that takes a number x as input, then for each number n from 2 to x - 1, test if x is evenly divisible by n. If it is, return False. If n
Solution 1:
You need to loop over the range:
defis_prime(x):
if x < 2:
returnFalsefor i inrange(2,x):
if x % i == 0:
returnFalsereturnTrue
if x % i == 0
never evaluates to True, you have a prime so you return True outside the loop after you have checked each i
. You could simply return a gen exp:
defis_prime(x):
return x > 1andnotany(x % i == 0for i inrange(2, x))
Post a Comment for "Python Calculating Prime Numbers"