sieve of eratosthenes seems slow

I think this function works as a sieve but it seems quite slow. Can someone suggest how I can make it faster?

Thanks!

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
 std::vector <bool> primes (MAX);
	
	//set to true

	for (long long int i=0; i < MAX; i++)
		primes [i] = true;

	
	//sieve

	for (long long int i= 2; i < sqrt(MAX); i++)
	{
		if (primes[i] == false)
			continue;

		for (long long int j=2;true; j++)
		{
			long long int total = j * i;
			
			if (total < MAX)
				primes [total] = false;
	
			else
				break;
		
			
		}

	}
Last edited on
1) Construct the vector with the value you want, rather than iterating over it:

 
std::vector<bool> primes(MAX,true); // <- all elements will be true, no need to loop 


2) Don't call sqrt() every time you loop. Record the value outside the loop and use that value instead:

1
2
auto end = sqrt(MAX);
for(long long i = 2; i < end; ++i)


3) Increment by 'i' in your inner loop rather than multiplying each time:

1
2
3
4
for(long long j = i; j < MAX; j += i)
{
    primes[j] = false;
}



4) Turn optimizations on. (ie: do a "Release build" rather than a debug build)
Last edited on
Topic archived. No new replies allowed.