Marcus
Marcus

Reputation: 23

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 returns False. Is there anyway to correct this?

def is_prime(x):
    if(x > 1):
        for i in range(2,x+1):
            if( x % i == 0):
                return False
            else:
                return True
    else:
        return False

Upvotes: 0

Views: 667

Answers (3)

Andrew
Andrew

Reputation: 39

Instead of doing this, you can also use SymPy module

import sympy

sympy.isprime(5)

Result :

True

Upvotes: 2

cdlane
cdlane

Reputation: 41872

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:

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

        return True

    return False

As others will point out, this is probably as inefficient a prime test as you can write. But it works.

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53525

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:

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

Upvotes: 1

Related Questions