“Prime or not” program

The are several problems with your program.

The first one is that the loop starting with statement

while (number1 == 5)

is infinite because number1 is not changed within the loop.

The second one is that you must always initialize variable a to zero within the loop. And it should be defined also within the loop because it is not used outside the loop. The same is valid for variable number.

Take into account that a number is prime if it is divisble by 1 and itself (except number 1). So I would initially set variable b to zero and compare it with 2. It is more clear than to compare it with 3.

The program can look the following way

#include <iostream>

int main()
{
    while ( true )
    {
        std::cout << "Enter your number and we'll tell you if it's prime or not (0-exit): ";

        unsigned int number = 0;
        std::cin >> number;

        if ( number == 0 ) break;

        unsigned int n = 0;
        unsigned int divisor = 0;

        while ( divisor++ < number )
        {
            if ( number % divisor == 0 ) n++;
        }

        if ( n == 2 )
            std::cout << "Your number is prime" << std::endl;
        else
            std::cout << "Your number is not prime" << std::endl;
    }
}

Browse More Popular Posts

Leave a Comment