回复 9楼 beyondyf
非常非常感谢版主的代码,我会花时间仔细看的,比如输入19,21, 405, 就会产生19个,21个405个连续素数的和,
问题的要求是这些和应该相同,所以是不是要继续做判断,
直到找到和相同的那个最小的素数吧
The quieter you become, the more you can hear
typedef unsigned long long bignum; struct primerec { bignum bn; struct primerec *next; }; void findPrimes(bignum topCandidate) { printf("2\n"); struct primerec *firstPrime = malloc(sizeof(struct primerec)); assert(firstPrime != NULL); struct primerec *latestPrime = firstPrime; firstPrime->bn = 3; firstPrime->next = NULL; bignum candidate = 3; while(candidate <= topCandidate) { struct primerec *thisPrime = firstPrime; int prime = 1; while(thisPrime->bn * thisPrime->bn <= candidate) { if(candidate % thisPrime->bn == 0) { prime = 0; break; } thisPrime = thisPrime->next; } if(prime ) { printPrime(candidate); latestPrime->next = malloc(sizeof(struct primerec)); assert(latestPrime->next != NULL); latestPrime = latestPrime->next; latestPrime->bn = candidate; latestPrime->next = NULL; } candidate += 2; } freeList(firstPrime); }
#include<stdio.h> #include<math.h> #define LENGTH_MAX 1000000 int prime[LENGTH_MAX] = {2, 3}; void init() { int i, j, k, q; for(i = 2; i < LENGTH_MAX; prime[i++] = j) for(j = prime[i - 1] + 2;; j += 2) { for(q = sqrt(j), k = 1; prime[k] <= q && j % prime[k]; k++); if(prime[k] > q) break; } } int is_prime(int a) { int from, to, p; for(from = 0, to = LENGTH_MAX - 1; from <= to;) { p = (from + to) >> 1; if(prime[p] > a) to = p - 1; else if(prime[p] < a) from = p + 1; else return 1; } return 0; } int find(int len, int * from) { int i, j, s; if(*from + len > LENGTH_MAX) return 0; for(s = i = 0; i < len; s += prime[*from + i++]); for(i += *from; i < LENGTH_MAX && !is_prime(s); i++) { s += prime[i] - prime[i - len]; if(s > prime[LENGTH_MAX - 1]) return 0; } if(i >= LENGTH_MAX) return 0; *from = i - len; return s; } void search(int plen, int * s, int * slen) { int from, i, j, a; for(from = i = j = 0; (a = find(plen, &from)) && a <= s[*slen - 1]; from++) { while(i < *slen && s[i] < a) i++; if(s[i] == a) s[j++] = a; } *slen = j; } int main() { int from, a; int s[1000], len; init(); for(from = len = 0; a = find(781, &from); from++) s[len++] = a; search(405, s, &len); search(21, s, &len); search(19, s, &len); if(len >= 1) printf("%d\n", s[0]); return 0; }