Abdul
Abdul

Reputation: 53

What's wrong with this python prime number function?

So I just want to check what's wrong with my function. It gives out prime numbers just fine but when I put in a number like 4, it prints "4 is not prime" then "4 is a prime number." What seems to be the error? (I know it's sad, but I spent 8 hours doing this(beginner)).

def isprime(n):
    if n == 1:
        print ("1 is not prime.")
    if n == 2:
        print ("2 is a prime number.")
    for x in range (2, n):
        if n%x == 0:
            print (n, "is not prime.")
        if n%x != 0:
            print (n, "is a prime number.")

Upvotes: 3

Views: 2532

Answers (2)

simonzack
simonzack

Reputation: 20968

Your algorithm is wrong, you need to break after a factor is detected, and print is a prime if there are no factors.

Here's a corrected version:

def isprime(n):
    if n == 1:
        print ("1 is not prime.")
        return
    if n == 2:
        print ("2 is a prime number.")
        return
    for x in range (2, n):
        if n%x == 0:
            print (n, "is not prime.")
            break
    else:
        print (n, "is a prime number.")

Upvotes: 4

MSalmo
MSalmo

Reputation: 372

You should add a break statement right under print(n, "is not prime."), otherwise it will continue to loop through all the numbers until n, which would be unnecessary.

Upvotes: 0

Related Questions