Hey all!
I was bored today so I wrote a function that calculates all prime numbers between 2 and n. So I looked up a few ways to do it. There are quite alot options to calculate primes but I ended up with the Sieve of Eratosthenes.
This option might not be the most efficient nor the easiest but it was fun to make. On my laptop it calculated the prime numbers between 0 and 100,000 in 5,042 milliseconds. I intentionally didn't use a STL container. If you got any comments just post them below. I hope someone can learn from this.
code:
I was bored today so I wrote a function that calculates all prime numbers between 2 and n. So I looked up a few ways to do it. There are quite alot options to calculate primes but I ended up with the Sieve of Eratosthenes.
This option might not be the most efficient nor the easiest but it was fun to make. On my laptop it calculated the prime numbers between 0 and 100,000 in 5,042 milliseconds. I intentionally didn't use a STL container. If you got any comments just post them below. I hope someone can learn from this.
code:
Code
#include <iostream>
/*
calculates prime numbers between 0 and n.
the amount of primes calculated will be assigned to primes, so you can loop through the array
returns a pointer to an dynamically allocated int array
*/
int* sieve(int n, int& primes)
{
int *arr = new int[n];
//fill array
for(int i = 0; i < n; ++i)
{
arr[i] = i;
}
//By definition 0 and 1 are not prime
arr[0] = -1;
arr[1] = -1;
//set every number that's not prime to -1
int ps[4] = {2, 3, 5, 7};
for(int i = 0, p = ps[0]; i < 4; ++i, p = ps[i])
{
for(int i = p + p; i < n; i += p)
{
arr[i] = -1;
}
}
//assign every prime number to the beginning of the array
int index = 0;
for(int i = 0; i < n; ++i)
{
if(arr[i] != -1)
arr[index++] = arr[i];
}
primes = index; //index contains the amount of prime numbers calculated now
//free the remaining unused memory
int *ptr = &arr[index];
delete [] ptr;
//return the array containing the prime numbers
return arr;
}
int main()
{
int sz;
int *arr = sieve(300, sz);
//print out prime numbers
for(int i = 0; i < sz; ++i)
std::cout << arr[i] << std::endl;
delete [] arr;
return 0;
}
