程序代码:
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#define max 15485864
char is_prime_p[max] = {0};
unsigned long long int nth_prime_sum[1000001] = {0};
int main(int argc, char *argv[]) {
int i, j, l = 2;
// Sieve to get primes and the sums.
for (i = 3; i < max; i += 2) {
is_prime_p[i] = 1;
}
nth_prime_sum[1] = 2;
for (i = 3; i < max; i += 2) {
if (is_prime_p[i]) {
nth_prime_sum[l] = nth_prime_sum[l - 1] + i;
l++;
for (j = i * 3; j < max; j += i << 1) {
is_prime_p[j] = 0;
}
}
}
// The following printf() is for mingw only.
// Please modify the format string according to
// your compiling environment.
printf("Sum of first 1,000,000 primes is %I64u\n",
nth_prime_sum[--l]);
if (argc > 1 && strcmp(argv[1], "-q") == 0) {
printf ("Give me an integer n, and I'll tell you the "
"sum of first n primes.\n"
"Intput any non-numeric character, a number bigger "
"than 1,000,000 or a negative number to quit\n"
"n: ");
// Allows the user to do queries.
while (scanf("%d", &l) == 1 && l <= 1000000 && l >= 0) {
while (getchar() != '\n');
printf (" %I64u\n\n", nth_prime_sum[l]);
printf("n: ");
}
}
return 0;
}
运行程序的时候加参数 -q 可以自由查询前 n 个质数的和 (0 <= n <= 1,000,000)。
直接运行计算前 1,000,000 个质数的和。
mingw time 显示运行时间 641ms,内存 24MB 以下
gcc -O3 的话直接运行时间 600ms 以下
[
本帖最后由 voidx 于 2011-8-21 14:36 编辑 ]