0

any one please explain me the below code please step by step

Below code prints prime number but i want to know why factors (variable) has 1 and 2 and then 3 and 4 value in last as its intial vale is 0 then factors++ increase its value by 1 so its final value must be 1... please explain me thank u ----------------------------------------------------------------------------------- #include <iostream> using namespace std; int main() { cout<<"2 is prime"<<endl;/*my code skips even numbers to make it faster so i had to manualy output the only even prime number*/ int num=1; while (num < 110){// change for more int factors = 0; num++; if(num%2==0){ num++; } for(int i =1; i<=num; i+=2){ if (num%i==0){ factors++; cout << "factor value " << factors << endl; // just to show value of factors } } if (factors == 2){ cout<<num<<" is prime"<<endl; } } return 0; }

15th Aug 2016, 8:16 AM
raj
raj - avatar
1 Antwort
+ 1
It can be more than 1. We know a number is prime when it has 2 factors :itself and 1. So the program checks for the number of factors and it could be more than 2 . Think of 4, it can be divided by 4,by 1 and by 2 so the value is an integer which means the number of factors is 3. Factor is 0. Can for example 5 be divided by itself? 5/5 Yes. Factor = 1 Can 5 be divided by ? 5/1 Yes. Factor = Factor + 1 (or Factor++) So it is 2 now. Does the number have only 2 factors? Yes, 5 and 1 . The number is prime. I think thats how it works ..
15th Aug 2016, 9:20 AM
Vlad Cranga
Vlad Cranga - avatar