#include <iostream>
using namespace std;
int main(){
int num;
bool isPrime = true;
cout<<"Enter any number to verify if it is a prime number?: ";
cin>>num;
int m= num/2;
for (int i = 2; i<=m; i++){
if(num%i == 0){
isPrime = false;
break;
}
}
if(isPrime){
cout<<"The number "<<num<<" is prime. "<<endl;
}else{
cout<<"The number "<<num<<" is not prime."<<endl;
}
return 0;
}
Output:
In Case Of Prime Numbers:
In Case Of Non-Prime Numbers:
Working Of The Program:
The program checks if the number is prime or not. Here is how it works: 1. It starts by declaring an integer variable called
num
to store the user input and a boolean variable called isPrime
to keep track of whether the number is prime or not.2. The user is prompted to enter a number to check if it is prime.
3. The input number is read from the user and stored in the
num
variable using the cin
statement.4. The value of
num
is divided by 2 and stored in a new integer variable called m
. This value will be used as the upper limit for the loop that checks if the number is prime.5. A
for
loop is used to iterate through all the numbers between 2 and m
. For each iteration, the loop checks if the input number num
is divisible by the current value of i
. If it is divisible by I
, then isPrime
is set to false
and the loop is exited using the break
statement. If the loop finishes without finding a divisor for num
, then isPrime
is still set to true
, indicating that the number is prime.6. Finally, an
if-else
statement is used to print the appropriate message depending on whether the number is prime or not. If isPrime
is true
, then the number is prime and the message "The number num
is prime" is printed to the console. Otherwise, the number is not prime and the message "The number num
is not prime" is printed instead.7. Overall, this program is an implementation of a classic algorithm for checking if a number is a prime, and it uses a boolean flag to keep track of the result of the algorithm.
No comments:
Post a Comment