Whats the problem

I have recently tried to make a sieve for project Euler. it works for 10, but not for 2 million, please see if you can find the error:

Sieve.cpp
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
#include "sieve.hpp"
#include <iostream>
using namespace std;

Sieve::Sieve(long long n) {
	Sieve::n=n;
	index=0;
	total=2;
	if(n%2==0){
		ArrayLen=(n-2)/2;
		Array=new int[ArrayLen];
	}
	else{
		ArrayLen=(n-1)/2;
		Array=new int[ArrayLen];
	}
	for(int i=0; i<ArrayLen;i++) {Array[i]=1;}
}

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

unsigned long long Sieve::calc() {
	while(index<ArrayLen) {
		while(Array[index]!=1 && index<ArrayLen){index++;}
		for(unsigned long long i=((2*index)+3); i<ArrayLen;i+=((2*index)+3)) {
            Array[i]=0;
		}
		index++;
	}
	for(unsigned long long i=0; i<ArrayLen; i++) {
		if(Array[i]==1) {total+=((2*i)+3);}
}
return(total);
}

int main() {
    Sieve s(2000000);
    cout<<s.calc()<<endl;
}


sive.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef SIEVE
#define SIVE

class Sieve {
	public:
		Sieve(long long n);
		~Sieve();
		unsigned long long calc();
	private:
		long long n;
		int ArrayLen;
		int *Array;
		unsigned long long index;
		unsigned long long total;
};

#endif
Please limit the scope of your variables.
¿What do you mean with "It doesn't work"?

Also, explain the 2*index+3 (btw, this isn't smalltalk, there are precedence rules in the operators)
Last edited on
186240581510
for 2 m
4469579551475
for 10 m

Sooo What are you expecting at least?
Topic archived. No new replies allowed.