Project Euler #10

NO SPOILERS PLEASE!!!

This is the code i am using, it works fine for the test example, but the answer for s(2000000) is incorrect, what am i doing wrong.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include "SieveE.hpp"
#include <cmath>
#include <iostream>
using namespace std;

SieveE::SieveE(int n) {
	Array=new int[n];
	ArraySize=n;
	for(int i=0; i<n; i++) {
		Array[i]=1;
	}
	index=0;
	calculate();
}

SieveE::~SieveE() {
	delete[] Array;
}

int SieveE::nextPrime() {
    if(index<ArraySize-1){
        while(Array[index++]!=1 && index<ArraySize){
            if(index>=ArraySize-1){
                return(-1);
            }
        }
        return(index);
    }
    return(-1);
}

void SieveE::calculate() {
	Array[0]=0;
    for(int p=2; p<=sqrt(ArraySize); p++) {
        for(int i=2; i*p<=ArraySize; i++) {
            Array[(p*i)-1]=0;
        }
    }
}

int main() {
	SieveE s(1999999);
	unsigned long a=0;
	unsigned  long total=1;
	while(a!=-1) {
        a=s.nextPrime();
        total+=a;
	}
	cout<<total<<endl;
	return(0);
}
Last edited on
unsigned long isn't large enough for the result, try unsigned long long. I don't know if that is the issue you are having, I only skimmed the code.
Topic archived. No new replies allowed.