Hi my goal is to write a program where I can check whether a number is prime. However, I have made an error in my code that I'm not sure how to fix. For example, if I input 15, which is not a prime number, it prints out both "num is not a prime number" and "num is a prime number".
num = int(input("Enter a positive number to test: "))
while num < 0:
print("Invalid input, try again")
num = int(input("Enter a positive number to test: "))
prime = False
for i in range(2,num):
if num % i == 0: #if remainder is zero, then there is a factor
print(i, "is a factor of", num, "...stopping")
print("")
print(num, "is a not a prime number")
break
if num % i != 0:
print(i, "is not a divisor of", num, "... continuing")
prime = True
if prime == True: #once the condition from earlier is met, then it'll prove it's a
prime numer
print(num, "is a prime number")
CodePudding user response:
When trying to determine if a number (N) is prime, your first test is to see if it's less than 2. If that condition is met then it's not prime. From then on you need to check the modulus of N with a range of prime numbers up to the square root of N. So then it's a question of how to generate prime numbers quickly and efficiently and this has been answered many times in Stackoverflow. There are also strategies for determining probability of N being prime (usually only used for very large numbers)
CodePudding user response:
Here is the output from your code.
Enter a positive number to test: 15
2 is not a divisor of 15 ... continuing
3 is a factor of 15 ...stopping
15 is a not a prime number
15 is a prime number
The problem is in your bool variable prime. Before the for-cycle you assign it FALSE value. Every time in for-cycle when the number is not divided by i, you assign TRUE to prime variable. So if the second condition is met for once, your code always prints:
given_number is a prime number
You should change the logic of your code. Before the for-cycle always assume that the given number is prime number(prime = True
).
prime = True
for i in range(2,num):
if num % i == 0: #if remainder is zero, then there is a factor
print(i, "is a factor of", num, "...stopping")
print("")
print(num, "is a not a prime number")
prime = False
break
if num % i != 0:
print(i, "is not a divisor of", num, "... continuing")
CodePudding user response:
num = 13
if num > 1:
for i in range(2, num//2):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")