C++ Program to check whether the given number is prime or not



What is a prime number?

Prime numbers are positive integers having only two factors, 1 and the integer itself. Or in simple words you can say is a number which is divisible by itself and by 1.
For example: 11 is only divisible by 11(itself) and by 1. So it is a prime number. Now lets take 16, 16 is divisible by 1,2,4,8,16. 16 is not only divisible by 1 and 16 but also divisible 2,4,8. So it is not a prime number.

Lets see the algorithm,

Algorithm:

Step 1: Start.

Step 2: Read n.

Step 3: Initialize counter variable i to 2.

Step 4: if i <n go to step 5 otherwise go to step 7.

Step 5: if n is divisible i  write "It is a Prime" and go to step 8 otherwise go to step 6.

Step 6: Increment counter variable i by 1 and go to step 4.

Step 7: Write "It is a Prime".

Step 8: Stop.

Program:

 #include <iostream>  
 using namespace std;  
 int main()  
 {  
   int n , i;  
   cout<<"Enter the number you want check: ";  
   cin>>n;  
   //loop to check no. is prime or not  
   for(i = 2 ;i < n ; i++)   
   {    
   //if any no. between 1 and n is divisible by n then it's not a prime no.  
    if(n%i==0)   
    {  
      cout<<n<<"is Non Prime";  
      return 0;  
    }  
   }  
   cout<<n<<"is a Prime number";  
   return 0;  
 }  

Output:

Enter the number you want to check:57
57 is a Prime number
C++ Program to check whether the given number is prime or not C++ Program to check whether the given number is prime or not Reviewed by Beast Coder on January 16, 2021 Rating: 5

No comments:

Powered by Blogger.