View Single Post
Old Nov 2nd, 2006, 2:02 AM   #24
andro
Professional Programmer
 
Join Date: Oct 2005
Location: California
Posts: 319
Rep Power: 4 andro is on a distinguished road
Send a message via AIM to andro
Wrote this about a year ago, dug it up when I saw this...

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

void sieve(int n, int *primes);

int main(int argc, const char **argv)
{
    if (argc < 2)
		return -1;

    int n = atoi(argv[1]);
    int *primes = calloc(n, sizeof(int));
    int numprimes = 0;
    
    struct timeval timea, timeb;
    
    for (int i = 2; i < n; i++) 
    {
        *(primes+i) = 1;
    }
    
    gettimeofday(&timea, NULL);
    sieve(n, primes);
    gettimeofday(&timeb, NULL);
    
    
    for (int i = 0; i < n; i++) 
    {
        if (*(primes+i))
        {
            numprimes++;
        }
    }
    
    int delta_s     = timeb.tv_sec  - timea.tv_sec;
    int delta_us    = timeb.tv_usec - timea.tv_usec;

    float delta     = delta_s + delta_us / 1000000.0;
    
    printf("Took %f millseconds.\n", delta*1000);
    printf("Found %d primes.\n", numprimes);
    
    return 0;
}

void sieve(int n, int *primes)
{
    int max = floor(sqrt(n));

    for (int i = 2; i <= max; i++)
    {

        if (*(primes+i))
        {
            for (int j=i*i; j <= n; j+=i)
            {
                *(primes+j) = 0;
            }
        }
    }

}

mbp:~/Desktop andro$ ./sieve 10000000 
Took 528.309998 millseconds.
Found 664579 primes.
andro is offline   Reply With Quote