Prime number

ok here is the problem I want to solve. What is the sum of the first 250 prime numbers?

Here is what I have coded. It somehow does not work can you help me? It's just not the proper sum that it gives me

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

using namespace 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) return true;
    for(int y = 3; y <= 1 + (int)sqrt((double)x); y += 2)
        if(x % y == 0) return false;
    return true;
}

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.
Last edited on
I apoligize but can you clarify your sentence? I do not know what you mean that I am finding "number which is not relatively prime to x"
Last edited on
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
vector<int> vPrimeNumbers;
vPrimeNumbers[0] = 1;
vPrimeNumbers[1] = 2;

int nPrimeCandidate = 3;
while (vPrimeNumbers.size() < 250)
{
     bool bPrime = true;
     for (int & nVerifiedPrime : vPrimeNumbers)
     {
           if((nPrimeCandidate % nVerifiedPrime) == 0)   
           {
                bPrime = false;
                break;
           }
     }

     if (bPrime)
     {
            vPrimeNumbers.push_back(nPrimeCandidate);
     }
     nPrimeCandidate += 2;
}


Then after you have the first 250 prime candidates, you can add them up in a second step.
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.
Topic archived. No new replies allowed.