The sieve of eratosthenes
D
/* Sieve of Eratosthenes in D
* Written by Rob Hoelz
*/
import std.stdio;
import std.string;
void removeMultiples(int[] primes, int base) {
int mult = base * 2;
while(mult < primes.length) {
primes[mult] = 0;
mult += base;
}
}
int nextPrime(int[] primes, int currPrime) {
for(int i = currPrime + 1; i < primes.length; i++) {
if(primes[i]) {
return i;
}
}
return primes.length;
}
void generatePrimes(int[] primes) {
long currPrime = 2;
while((currPrime * currPrime) < primes.length) {
removeMultiples(primes, currPrime);
currPrime = nextPrime(primes, currPrime);
}
}
int main(char [][] args) {
int[] primes;
if(args.length > 1) {
long limit = atoi(args[1]);
primes = new int[limit + 1];
primes[0] = primes[1] = 0;
for(int i = 2; i <= limit; i++) {
primes[i] = 1;
}
generatePrimes(primes);
foreach(index, isPrime; primes) {
if(isPrime) {
writef("%d ", index);
}
}
writefln("");
}
return 0;
}
stats
It is
Friday December 05, 2008 10:48 am
This page served 952 times
This page last modified: April 14, 2008 11:28 am
Your IP address is: 38.103.63.61
You are browsing using: CCBot/1.0 (+http://www.commoncrawl.org/bot.html)
You are browsing from: United States.
badcomputer.org's uptime: 10:48:55 up 24 days, 14:59, 2 users, load average: 0.00, 0.00, 0.00
local
home | unix stuff | dir2ogg | sneetchalizer | wmainfo | q&d guide to permissions | q&d guide to tar and gzip | code | MS rant | browser shootout | linux & iAudio X5 | photos | music | programming poetry | sieve of Eratosthenes | plea | rain | suffer | archive | about | recipes | compaqr3000 | sitemap
search
credits
This page, and all pages on this site were created and are maintained by Darren Kirby using valid XHTML 1.0 and CSS, and are ©copyright 2002 - 2008. The Penguin image was created by Tukka, and is used by permission. Inspiration for the look of this site was provided by Eric A. Meyer's CSS gallery. This website runs on Gentoo Linux. It is served by Apache. PHP and MySQL hold together the backend.