[ create a new paste ] login | about

Link: http://codepad.org/Yu1R8mIO    [ raw code | output | fork ]

programmingpraxis - C, pasted on Nov 16:
/* sum of primes less than two million */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define ISBITSET(x, i) (( x[i>>3] & (1<<(i&7)) ) != 0)
#define SETBIT(x, i) x[i>>3] |= (1<<(i&7));
#define CLEARBIT(x, i) x[i>>3] &= (1<<(i&7)) ^ 0xFF;

long sumPrimes(long n)
{
    char b[(n+1)/8+1];
    int i, p;
    long sum = 0;

    memset(b, 255, sizeof(b));

    for (p=2; p<=n; p++)
    {
        if (ISBITSET(b,p))
        {
            sum += p;
            for (i=p; i<=n; i+=p)
            {
                CLEARBIT(b,i);
            }
        }
    }

    return sum;
}

void main(void)
{
    printf("%ld", sumPrimes(2000000));
}


Output:
1
1179908154


Create a new paste based on this one


Comments: