cpp check prime number is or not
In this example, the solution to finding the prime number in the cpp programming language.for doing this you should learn the following topics.
in the cpp language.
Code of prime number:
#include <iostream>
using namespace std;
int main() {
int var, n;
bool Prime = true;
cout << "Enter a positive integer: ";
cin >> n;
if (n == 0 || n == 1) {// 0 and 1 is already prime numbers
Prime = false;
}
else {
for (var = 2; var <= n -1; ++var) {
if (n % var == 0) {
Prime = false;
break;
}
}
}
if (Prime)
cout << n << " is a prime number";
else
cout << n << " is not a prime number";
return 0;
}
Here,in the above example take input from the user by input method and then check number is 0 or 1 then they are the prime number. After that for loop is used to check any number is divide our user number.
The incremental loop is executed till (n-1), check any number divides the original n or not by modulus.if (n % var == 0) this check will do in the problem check all the numbers between n and 2.
if (n % var == 0) is true then it is not prime else it is prime .In the end, is prime (is true or false) true display the prime number and false display the is not.
here, any problem in understanding the code comment below , we will very happy to entertain you in the understand of the code.
Comments
Post a Comment