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:

 def is_prime(x):
    if x < 2:
        return False
    for i in range(2,x):
        if x % i == 0:
            return False
    return True

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:

def is_prime(x):
    return x > 1 and not any(x % i == 0 for i in range(2, x))

Solution 2:

That's not how you use range.

You want

def is_prime(x):
    for n in range(2, x-1):
        if x % n == 0:
            return False
    return True

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"