1

I'm trying to find out whether a given number is prime or not. For example, when I enter the input as 5, it should output "5 is a prime".

However, I get multiple, conflicting outputs.

This is my code:

num = int(input("Enter the number: "))
if num > 1:
  for i in range(2,num):
    if (num % i) == 0:
      print(num,"is not a prime number")
      #print(i,"times",num//i,"is",num)
      break
    else:
        print(num,"is a prime number")
        # if input number is less than
        # or equal to 1, it is not prime
  else:
          print(num,"is not a prime number")

Output is:

Enter the number: 5

5 is a prime number
5 is a prime number
5 is a prime number
5 is not a prime number

The above output shows that 5 is prime number thrice and that 5 is not a prime number once. What is my mistake?

5
  • 5 % 2 = 1 - prints "is a prime number". 5 % 3 = 2 - same. 5 % 4 = 1 - same. Then you finish the loop, so final else runs, printing "is not a prime number" Commented Jun 26, 2024 at 8:02
  • your line printing that 5 is a prime number is in your for loop, so everytime you check a number to see if 5 is divisible by it, it finds it's not and prints 5 is prime each time. You need to check all the numbers first, then print 5 is prime if its not divisible by any of the numbers Commented Jun 26, 2024 at 8:03
  • 1
    Your loop is going in the range (2,num). You might soon understand that the range (2,Roundup(sqrt(num))) is also fine :-) Commented Jun 26, 2024 at 8:12
  • Try writing a separate function that determines if a number is prime (or not). Then, call that based on the user input. You'll see that that approach simplifies your code considerably Commented Jun 26, 2024 at 9:34
  • You might also want to have a look at the answers to this question or at this article. Both deal with implementing the Sieve of Eratosthenes in Python, which is a traditional algorithm for finding prime numbers. Commented Jun 26, 2024 at 11:53

1 Answer 1

1

There are two problems:

  1. You cannot know whether a number is prime before having done all iterations of the loop, so the inner else block is taking conclusions too soon. It might be there is still a value for i coming that is a divisor of num. So remove this inner else

  2. The outer else prints a wrong message. This executes when no break was executed in the loop, i.e. when no divisor was found. So in that case you should print it is a prime number.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.