Can anyone explain the logic behind the prime number prog in C++?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can anyone explain the logic behind the prime number prog in C++??

13th Mar 2017, 1:35 AM
Gaurav Pandit
Gaurav Pandit - avatar
3 Answers
+ 3
thanks @devender &@rohan
13th Mar 2017, 6:13 AM
Gaurav Pandit
Gaurav Pandit - avatar
+ 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.
13th Mar 2017, 4:33 AM
Rohan
Rohan - avatar
+ 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"; }
13th Mar 2017, 6:07 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar