Problem: Prime Number Checker
Write a C++ program that checks whether a given number is prime or not. A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.
Your program should take an input number from the user and output whether it is prime or not.
Example:
Enter a number: 17
17 is a prime number.
Enter a number: 21
21 is not a prime number.
Remember, you should not use any external libraries or functions to solve this problem. You can only use the basic features of the C++ language.
Hint: To check if a number n
is prime, you can iterate from 2 to n/2
and check if n
is divisible by any number in that range. If it is divisible by any number, then it is not prime.
You can start by writing the skeleton of the program and then gradually fill in the missing parts to complete the solution. Let me know if you need further assistance!
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (number < 2) {
cout << number << " is not a prime number" << endl;
} else {
bool isPrime = true;
for (int i = 2; i <= sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
cout << number << " is a prime number" << endl;
} else {
cout << number << " is not a prime number" << endl;
}
}
return 0;
}
In this code, I got the
number
for the input and then used the if statement to compare whether the number fulfills the expectation of being a prime number by comparing it to 2 and after that, using a boolean to iterate if the number is a prime number and used the for loop from 2 to the square root of thenumber
. Once the boolean turns into a false statement it stops. Lastly, using an if statement, when theisPrime
is true, it will print the number is a prime number. If not, the number is not a prime number.