Skip to content

Instantly share code, notes, and snippets.

@menjaraz
Created July 18, 2024 08:26
Show Gist options
  • Save menjaraz/a0f7eee18f8f8942e3f55d102d167016 to your computer and use it in GitHub Desktop.
Save menjaraz/a0f7eee18f8f8942e3f55d102d167016 to your computer and use it in GitHub Desktop.
ProjectEuler: Summation of Primes
import std.stdio : writefln;
void main() {
"%,3?d".writefln('_', 2_000_000.sumOfPrimesBelow);
}
ulong sumOfPrimesBelow(ulong num) {
// Create a dynamic array of booleans initialized to true
bool[] primes = new bool[num];
primes[] = true;
// Set 0 and 1 to false (not primes)
primes[0] = false;
primes[1] = false;
ulong sum = 0;
// Sieve of Eratosthenes
for (ulong p = 2; p < num; p++) {
if (primes[p]) {
sum += p;
for (ulong m = p * p; m < num; m += p) {
primes[m] = false;
}
}
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment