Prime number calculator
Write a C++ program that takes a user input and checks if it's a prime number.
Use a while loop to check every possible number for divisors.
Hint
The modulus
%operator can be used to check if a number is perfectly divisible by another.x % y == 0is will never be true ifxis a prime number, unlessy == x.
If no factors are found before the square root of a number, it confirms that the number is prime.
Answer
#include <iostream>
#include <cmath>
int main() {
// Get the input from the user
int input;
std::cout << "Enter a number: ";
std::cin >> input;
// If we cannot prove that the number is not prime, then it is prime, so we assume it is prime.
bool isPrime = true;
// If the number is less than 2, it is not prime.
if (input < 2)
isPrime = true;
// Check if the number is divisible by any number between 2 and the square root of the number.
// If we find out that it's not prime, we can stop checking.
int counter = 2;
while (counter <= sqrt(input) && isPrime) {
if (input % counter == 0) {
// If the number is divisible it is not prime.
isPrime = false;
}
counter++;
}
// Print the result
if (isPrime)
std::cout << input << " is a prime number.\n";
else
std::cout << input << " is not a prime number.\n";
}