In: Computer Science
Hi,
Please find the below code in CPP with description:
#include <iostream>
using namespace std;
int main() {
//Declare variables
int i, userInput;
//Declare boolean Variable
bool isPrime = true;
//Show Message tot end user and Get Input from user
cout << "Enter a positive integer: ";
cin >> userInput;
// 0 and 1 are not prime numbers
if (userInput == 0 || userInput == 1) {
//Set boolean value to false if number are 0 or 1 entered by user without checking any calculations
isPrime = false;
}
else {
//Number for other than 0 or 1, we need to do calculations to check number is prime or NOT
//loop start from 2
//first try dividing it by 2, and see if you get a whole number
for (i = 2; i <= userInput / 2; ++i) {
if (userInput % i == 0) {
//If you don't get a whole number, next try dividing it by prime numbers: 3, 5, 7, 11
//(9 is divisible by 3) and so on
//if number is divisibly by 2 then its not a prime number
isPrime = false;
break;
}
}
}
//here check the boolena flag and accordinly print the message
if (isPrime)
cout << userInput << " is a prime number";
else
cout << userInput << " is NOT a prime number";
return 0;
}
In the above example, 55 is divisible by 5 and 11 so 55 is NOT prime number
In case of 71, this number is not divisible by any number so 71 is prime number.
Thanks.