C++ Program to check a Prime Number.

To write code for Prime number checking first we need to understand what is Prime Number? Any number which is divisible only itself and 1 is known as Prime Number. Example: 2, 3, 5, 7, etc. You cannot divide these numbers with any other number except 1 and itself but one thing to make sure of here is that 0 and 1 are not Prime Numbers.


We can follow the below instructions to check if a number is Prime or not:

  • Create a boolean flag is_prime and mark and initially initialize it with true.
  • Check if the given number n is 0 or 1, if yes then set the is_prime flag value equal to false and print a message that the given number is not prime. 
  • If the n is greater than 1 then run a for loop from i = 2 up to i <= n/2 where n is the number that we need to check. Keep on incrementing the value of i by 1 with each iteration.

Note: We are running the loop up to n/2 because it is not possible to find any factor of n beyond n/2.(alert-passed)

  • In any iteration, the value of i perfectly divides the given value n then set the is_prime flag value equal to false and prints a message that the given number is not prime, else prints a message that the given number is a prime number.

Example: C++ Code to check Prime Number.

//C++ Code to check prime number
#include<iostream>
using namespace std;

int main(){

    int n;
    bool is_prime = true;

    cout<<"Enter a positive number: ";
    cin>>n;

    if(n == 0 || n == 1)
       is_prime = false;

    for(int i = 2; i <= n/2; i++){
        if(n % i == 0){
            is_prime = false;
            break;
        }
    }   

    if(is_prime)
       cout<<n<<" is a prime number.";
    else
       cout<<n<<" is not a prime number.";

    return 0;                    
}
Output:
Enter a positive number: 7
7 is a prime number.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS