Welcome back to the last Monday in March!
Today's problem will be to reimplement a classic algorithm for finding small primes. The Sieve of Eratosthenes has been around for centuries. Follow the link to the Wikipedia page to learn the idea behind the algorithm then implement it in a language of your choice.
Comments:
David - 9 years, 8 months ago
Python with a touch of feature creep.
reply permalink
Jack le - 9 years, 8 months ago
This was actually an assignment in my system level programming class. The program is actually to solve project euler 10.
#include <stdio.h>
int main(){ // This program uses the sieve of Eratosthenes to solve the problem. int numbers[2000000] = {}; //Create an array of 2000000 integers of value 0 long int sum = 0; // Initialize sum to 0 // Create i and j for the nested for loops, they have to be long int because j*j will exceed the limit of int at some point long int i, j; for(j = 2; j <= sizeof(numbers)/4; j++){ // j goes from 2 to n if(!numbers[j-1]){ // If the number is not marked sum += j; // That is a prime number and add it to sum for(i = j*j; i <= sizeof(numbers)/4; i+=j) // Mark all the numbers from j2 to the end by j interval numbers[i-1] = 1; } } printf("sum: %ld\n",sum); // Display the sum return 0; }
reply permalink
Werner D - 9 years, 8 months ago
C# solution:
reply permalink
Anonymous - 9 years, 8 months ago
I've run this with up to 10 million which takes about a minute. Haven't tried 100 million.
reply permalink