Input a positive integer from the user and determine whether the number is a prime number or not.
#include <iostream>
int main()
{
int num;
std::cout << "Enter a positive integer: ";
std::cin >> num;
bool is_prime = true;
if (num < 2)
{
is_prime = false; // 0 and 1 are not prime
}
else
{
for (int i = 2; i <= num / 2; ++i)
{
if (num % i == 0)
{
is_prime = false;
break;
}
}
}
if (is_prime)
std::cout << num << " is a prime number";
else
std::cout << num << " is not a prime number";
return 0;
}
Comments
Leave a comment