Sunday 13 May 2018

To check whether a number is prime or not?

C++ program to find a number is prime or not?

Algorithm:

Input = number

set counter=0;

set i=0 to i<=number

if(number%i==0)
counter=counter+1;
 i=i+1;
if(counter == 2)
print"number is prime";

else
print "number is not prime";
    
exit;
    
Approach to solve:

Input = 5;
number%i=5%1=0
5%2=1
5%3=2
5%4=1
5%5=0

counter=2
so, it will print number is prime.

Input =4
number%i=4%1=0
4%2=0
4%3=1
4%4=0

counter=3
so, it will print number is not prime.

Program:-
#include<iostream>

using namespace std;
//function for prime number
int prime(int num){
 
 int count=0;
 if(num==1){
  return 0;
 }
 
 for(int i=1; i<=num; i++){
  
   if(num%i==0)
     count++;
 }
 
 if(count==2){
  cout<<"Number is Prime ";
 }
 
 else
 {
  cout<<"Number is not prime ";
 }
 
}

int main(){
 
 int num1;
 
 cout<<"Enter any number:";
 cin>>num1;
 
 prime (num1);  //function calling
 
 return 0;
}

Output:-
Enter any number:3
Number is prime

Enter any number:88
Number is not prime


HAPPY CODING...

0 comments:

Post a Comment