prime number checking program

closed account (EAXiz8AR)
So I'm trying to make a program that checks if the inputted number is prime.

"a" is the inputted number and the code checks to see if the number is a prime or not. It works except that when you put in something like 81 for a, it outputs "The number input was not prime number" twice. Can you help me figure out why its doing that?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
      if (a%2 == 0)
      {
         cout << "The number input was not prime number" << endl;
      }
      else if (a%2 != 0)
      {
         bool prime = true;
         for (int i = 2; i <= sqrt(a); i++)
         {
            if (a%i == 0)
            {
               prime = false;
               cout << "The number input was not prime number" << endl;
            }
         }
         
         if (prime == true)
         {
            cout << "The number input was a prime number" << endl;
         }
      }


Well, you're testing 81 for divisibility from 2 to 9. And it's divisible by 3 and 9. So that's the correct output for your code. (It should display the message 3 times for 105, 4 times for 225, and 5 times for 315)

Move the message out of the loop, as else of if (prime == true)

And if you want to give up as soon as you find the first numbers it's divisible by, use break; or prime to exit the loop.

Andy

PS You can also cut down on the number of tests you for loop is making, as you only need to check the odd numbers.
Last edited on
Topic archived. No new replies allowed.