Write C++ Program to check whether a number is a prime C number or not. There are many ways to check whether a number is a prime number or not. But most of the methods are based on trial and error and/or very difficult to implement in C++ Programming. So, here I have given a method to check whether a number is a prime number or not. If the number is not prime C then the program will print “Number is not prime”.
#include
#include
using namespace std;
int main()
{
int n,i,flag=1;
cout<<"Enter any number:";
cin>>n;
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=0;
break;
}
}
if(flag)
cout<<"\n"<<n<<" is a Prime number";
else cout<<"\n"<<n<<" is not a Prime number";
return 0;
}
Checking whether a number is a prime number or not is the basic concept of prime number. A prime number is a positive integer that is divisible only by 1 and itself. Every whole number except 1 and itself is a composite number.
It’s an important concept in many applications, especially in cryptography and number theory. Primality testing is also required for RSA, which is a common public key algorithm used in most secure communications.
In this article, I will explain the basic concept of checking whether a number is prime number or not in C++. It’s a simple procedure to implement.
The main idea is that if a number is composite, it must be divisible by some smaller numbers. So we can calculate the smallest such numbers until we find the smallest multiple of the number that isn’t equal to the number. If that number is less than the original number, then the number is composite.
But how to find that number? Well, let’s find the first number in the sequence and take its multiples. Let’s start with the number 2. Take its first multiple, which is 2. Then take its second multiple, which is 4. And so on.
Let’s see what happens when we multiply 2 with 3. First, we get 6, and then 6 times 2, which is 12. So 2 and 3 are the smallest two numbers that aren’t equal to the original number. Now we can return that as the answer.
We can do this with any number. We start with the number 1, and keep taking its multiples until we get a number that isn’t equal to the original number.
Here is the another code snippet to demonstrate.
#include
#include
int main()
{
std::vector primes;
primes.push_back(2);
bool isPrime = true;
int n = 999999;
while (n!= 0) {
int multiples = 1;
for (int i = 1; i <= n / 2; ++i) {
multiples *= i;
}
int m = n % multiples;
if (m == 0) {
primes.push_back(multiples);
isPrime = false;
break;
} else {
n /= multiples;
}
}
if (isPrime) {
for (int i = 0; i < primes.size(); ++i) {
std::cout << primes[i] << '\t';
}
std::cout << std::endl;
}
}