Skip to content Skip to sidebar Skip to footer

Finding Prime Numbers In Python

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 retur

Solution 1:

Instead of doing this, you can also use SymPy module

import sympy

sympy.isprime(5)

Result :

True

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:
        returnFalse

Solution 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:
                returnFalsereturnTruereturnFalse

As 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"