+ 2

How this code work ?

int i, j, c; for(i=2; i<=100; i++) { c=0; for(j=2; j<=i; j++) { if(i%j==0) c++; } if(c<2) cout<<i; }

1st Mar 2017, 5:03 PM
Sofyan Maulana
Sofyan Maulana - avatar
5 odpowiedzi
+ 8
Sorry, I'm really late... but anyways this is what I've understood. loop 1 : which includes i, is the outer loop loop 2: which includes j, is the inner loop So loop starts with i loop, then c is assigned 0, then the inner loop is executed, inside which we are basically checking how many divisors 'i' has starting from 2 till 'i' itself. so loop is executed until j<=i ,this completes j loop, after coming out of j loop, the value of c is checked, which tells us how many divisors 'i' has, and if it is less than 2 it will print the value of i. This completes one loop cycle of i loop. In the next cycle the value of i is increased and c is assigned 0, and same thing goes on. As Akshata Bhat has already mentioned, this code is to check for prime numbers. But this codes takes extra useless efforts to find the primes.
4th Mar 2017, 8:51 AM
Saumya
Saumya - avatar
+ 6
this code is to check if the numbers are prime or not -prime numbers are only divisible by itself • the first loop is to iterate among the range you have provided • since prime numbers are only divisible by itself any number lower than itself wont give a 0 remainder on being divided by it. the j loop is to check all the numbers lower than the current number • incase the number is divisible by the number lower to it(j) the i never enters the if loop and c doesnt increase , hence the number is not printed • after checking all the numbers lower or equal to i i.e the j loop , the c is initialized to 0 •incase the the number is only divisible by itself c is incremented to 1 • only numbers where c is 1 is printed
1st Mar 2017, 7:12 PM
Akshata
Akshata - avatar
+ 6
ok so incase of 9 •i will be 9 •c=0 •j loop starts from 2 when it reaches 3 since it is divisible c = 1 •then the j loop continues till 9 • on reaching 9 , 9 is again divisible by 9 so c becomes 2 • but condition for print is that c should be less than 2 •hence 9 is not a prime number (in short you can say c keeps a count of how many times the number was divisible , prime numbers are only divisible by itself so the count will only go upto 1 , other numbers more than 1 , so they dont get printed)
2nd Mar 2017, 3:18 AM
Akshata
Akshata - avatar
+ 2
So the c is not increase untill the i divided by it self, and nothing lower number give 0 to if loop ? i'm still confuse.. for example : " c=0; for(j=2; j<=i; j++) { if(i%j==0) c++; " when they c=0 i=9 j=3 9%3=0 ===> (if(i%j==0) c++) why the c wasn't increased ? why the c increased when only the loop finished check all number ? why c not increased when there's a lower number that give it 0 result ? sorry for bad english
2nd Mar 2017, 12:32 AM
Sofyan Maulana
Sofyan Maulana - avatar
+ 2
Solved! Thanks Akshata Bhat 😆😅
2nd Mar 2017, 4:50 AM
Sofyan Maulana
Sofyan Maulana - avatar