+ 1
Can anyone explain the logic behind the prime number prog in C++??
3 Respostas
+ 3
thanks @devender &@rohan
+ 1
Let x be a number. For it to be prime, the number should not be divisible by any number (say y) from 2 till x/2 (except 1). We run a for loop to check (x)mod(y)!=0 from y=2 till x/2. If every time check is satisfied, then x is prime else not.
+ 1
Dear Gaurav,
I am putting the code below along with comments which may help you understand the logic
//Check whether given no is prime or not
/*
1. check the remainder of the number between range 2 and half of the
number. Starting divisor is 2 because it is the first prime no.
2. If no factor found, the number is prime otherwise not
*/
#include <iostream>
using namespace std;
int main (void){
int num,f,r,h;
cout<<"Enter number to be tested as prime no: ";
cin>>num;
//Half of the number:
h=num/2;
//Loop between 2 and the half of the number
cout<<num;
for (f=2;f<h;f++){
//Find the remainder of num w.r.t current value of f
r = num%f;
if (r==0){ //print value of f if remainder is zero
cout<<" is not a prime number ";
return -1; //exits the application
}
}
//this statement will be executed only on the successful
//compeletion of the loop.
cout<<" is a prime number";
}