Write a C++ program to accept a number input from the user and determine whether it is a prime number or not.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Input and Output Examples
Example 1:
- Input: 7
- Output: 7 is a prime number.
Example 2:
- Input: 12
- Output: 12 is not a prime number.
Algorithm to Check Prime Number
- Start the program.
- Prompt the user to enter a number.
- Read the number input.
- Iterate from 2 to the square root of the number.
- Check if the number is divisible by any integer in the range.
- If it is divisible by any integer, it is not prime; otherwise, it is prime.
- End the program.
Below is the C++ code to check whether a number is prime or not:
#include <iostream>
#include <cmath> // Include the cmath library for mathematical functions
using namespace std;
int main() {
// Declare variables to store the number and a flag to indicate whether it is prime
int num;
bool isPrime = true;
// Prompt the user to input a number
cout << "Enter a number: ";
cin >> num;
// Check if the number is less than 2
if (num < 2) {
isPrime = false; // Numbers less than 2 are not prime
} else {
// Iterate from 2 to the square root of the number
for (int i = 2; i <= sqrt(num); ++i) {
// If the number is divisible by any integer in this range, it is not prime
if (num % i == 0) {
isPrime = false;
break;
}
}
}
// Display the result based on the flag
if (isPrime) {
cout << num << " is a prime number." << endl;
} else {
cout << num << " is not a prime number." << endl;
}
// Ending the program
return 0;
}
Testing the Program with Different Input Values
- Input: 7
Output: 7 is a prime number. - Input: 12
Output: 12 is not a prime number.
Practice Problem
Write a C++ program to find and print all prime numbers less than a given number N. (Hint: You can use the prime-checking algorithm within a loop to iterate through numbers.)