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; }
2 ответов
+ 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;
}
0
visph Thank you for the correction. It works perfectly now!