0

Why is my code of finding and listing all prime numbers from 1 to z (where z is the input number) not working?

#include <iostream> using namespace std; int main() { int i,a,z; cin>>z; for(a=2;a<=z;a++) { for (i=1;i<=a;i++) { if (a%i==0) { z++; } } if (z==2) cout<<a<<endl; } return 0; }

22nd Jun 2021, 6:10 AM
Aprameya S
2 odpowiedzi
+ 3
because you are incrementing the input variable and never reset it ^^ corrected code to keep your logic: #include <iostream> using namespace std; int main() { int i,a,z,f; cin>>z; for(a=2;a<=z;a++) { for (f=0,i=1;i<=a;i++) { if (a%i==0) { f++; } } if (f==2) cout<<a<<endl; } return 0; }
22nd Jun 2021, 6:18 AM
visph
visph - avatar
0
visph Thank you for the correction. It works perfectly now!
22nd Jun 2021, 9:47 AM
Aprameya S