#include <iostream>
usingnamespace std;
int prime(int x);
main()
{
int x = 0, y = 0, z = 1;
while(z < 250)
{
y = prime(x) + y;
if (prime(x) != 0)
z++;
x++;
}
cout<< y << ' ' << x << ' ' << z << endl;
return 0;
}
int prime(int x)
{
int y,z;
for (y = 2; y < x; y++)
if ( x % y == 0)
return y;
return 0;
}
Your prime function is wrong. Instead of finding a prime greater than x, it is finding a number which is not relatively prime to x. You probably want this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
bool isPrime(int x)
{
if(x == 2) returntrue;
for(int y = 3; y <= 1 + (int)sqrt((double)x); y += 2)
if(x % y == 0) returnfalse;
returntrue;
}
int prime(int x)
{
if(x <= 2) return 2;
if(x % 2 == 0) ++x;
while(true)
{
if(isPrime(x)) return x;
x += 2;
}
}
Note that you will have to change your main function to use this.
Another thing to note - when you are calculating the 250th prime number, you are calling 'prime(250)' twice. Each call, you are looping from 2-250 (when really I think you want to be looping from 2 - the249thprime, which is 2 - 1579). Why not do something like:
Thank you for the help. But I have started studying c++ by myself few months a go and did not get this far yet. I know only the old 'c' arrays where you have to say how big they are. And never used the bool functions.