Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.")
like image 663
Abdul Avatar asked Feb 15 '26 09:02

Abdul


1 Answers

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.")
like image 148
simonzack Avatar answered Feb 17 '26 23:02

simonzack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!