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.")
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.")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With