Skip to content Skip to sidebar Skip to footer

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))

Solution 2:

That's not how you use range.

You want

defis_prime(x):
    for n inrange(2, x-1):
        if x % n == 0:
            returnFalsereturnTrue

Range returns a list, so your original code was checking to see if the list object was evenly divisible by n, instead of checking each element of the list.

Post a Comment for "Python Calculating Prime Numbers"