XiaoxiaoPu
2016-02-25 00:41:39 +08:00
啊哦,上面发的错了,这个才对
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static inline int getbit(int *bits, int i)
{
return (bits[i>>5] >> (i & 31)) & 1;
}
static inline void setbit(int *bits, int i)
{
bits[i>>5] |= (1 << (i & 31));
}
static inline void clrbit(int *bits, int i)
{
bits[i>>5] &= ~(1 << (i & 31));
}
int isqrt(int num)
{
register int x1 = num, x2;
do
{
x2 = x1;
x1 = (x1 + num / x1) / 2;
} while (x1 < x2);
return x2;
}
int main()
{
int n = 10000000;
int *bits;
bits = (int *)malloc(((n>>5)+1) * sizeof(int));
if (bits == NULL)
{
fprintf(stderr, "Out of memory.\n");
return 1;
}
for (int i = 0; i < ((n>>5)+1); i++)
{
bits[i] = ~0;
}
clrbit(bits, 0);
clrbit(bits, 1);
clrbit(bits, 4);
int end = isqrt(n);
for (int i = 2; i <= end; i++)
{
if (getbit(bits, i))
{
int j0 = n / i;
for (int j = 2; j <= j0; j++)
{
clrbit(bits, i * j);
}
}
}
long sum = 0;
for (int i = 2; i <= n; i++)
{
if (getbit(bits, i))
{
sum += i;
}
}
printf("%ld\n", sum);
return 0;
}
➜ ~ gcc -o prime -std=gnu99 -O3 prime.c
➜ ~ ./prime
3203324994356
➜ ~