Created
July 18, 2024 08:26
-
-
Save menjaraz/a0f7eee18f8f8942e3f55d102d167016 to your computer and use it in GitHub Desktop.
ProjectEuler: Summation of Primes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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