prime number betn 1 to 100 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

prime number betn 1 to 100

Can someone please explain to me what happens in the second loop when i=6 elaborately? //problem when i=6 and j=3 int main() { int num1,num2; int fnd=0 //1st for loop prime number counter , ctr=0;//2nd for loop counter; cout<<" Input number for starting range: "; cin>> num1;//1 cout << " Input number for ending range: "; cin>> num2;//100 cout << "\n The prime numbers between "<<num1<<" and "<<num2<<" are:"<<endl; for( int i= num1; i<=num2; i++) // 1 2 3 4 5 { for(int j=2; j<=sqrt(i); j++) // 1 2 3 not enter coz 2> 1.414...4 enter coz 2<=2 so j now becomes 3>root 5 so 5 not enter { if(i%j==0) //4%2==0 { ctr++; //1 always as ctr=0 at last } } if(ctr==0 && i!=1) //so ctr 1 !=0 not enter this condition //2 enter coz ctr == 0 2!=1 // 4 not enter coz ctr==1 { fnd++; //1 2 3 cout<< i << " "; // 2 3 5 } ctr=0; //again ctr =0 } cout<<endl<<"total prime numbers: " <<fnd; }

20th Apr 2021, 6:41 PM
Ramisa Fariha
Ramisa Fariha - avatar
2 Answers
+ 1
j can't be equal 3, when i=6, cuz max j value is j=sqrt(6) So if you cast sqrt(6)(=2,449) to int, it becomes lower integer, in this case it's 2 So it is not possible to have i=6 and j=3 at the same time
20th Apr 2021, 7:00 PM
Michal Doruch
0
thank you
20th Apr 2021, 7:17 PM
Ramisa Fariha
Ramisa Fariha - avatar