Test instructions
Given n, the number of schemes to write N as a sum of several successive primes.
Analysis:
This problem is very similar to the Great White book P48 example 21, which details how to optimize from an O (N3) algorithm to O (N2) to O (Nlogn), and finally to O (n) of the Divine General optimization.
First, sift out the prime number within 10000, put it in an array, and then find the prefix and B of the prime number. In this way, the first prime number is accumulated to the first J primes, which can be expressed as bj-bi-1
Enumerating the right endpoint J of a continuous subsequence, we want to find bj-bi-1 = N, which is to find Bi-1 = Bj-n.
Because BJ is incremented, so Bi-1 is also incremented, so we don't have to enumerate I from the beginning, but then the value of the last loop I continues to enumerate.
Also, because the prime number itself is also incremented (nonsense!), so J does not have to enumerate to the last prime number, as long as it is enumerated in a prime number not exceeding N.
Said so much, I just want to say that the efficiency of the algorithm is very high, 15ms,uva on the 300+ name, despise those playing table dog.
1#include <cstdio>2#include <cmath>3 4 Const intMAXN =10000;5 Const intMAXP =1300;6 BOOLVIS[MAXN +Ten];7 intPRIME[MAXP], Sum[maxp], cnt =1;8 9 voidInit ()Ten { One intm = sqrt (MAXN +0.5); A for(inti =2; I <= m; ++i)if(!Vis[i]) - for(intj = i * I; J <= Maxn; J + = i) vis[j] =true; - for(inti =2; I <= MAXN; ++i)if(!vis[i]) prime[cnt++] =i; thecnt--; - //the prefixes of primes and - for(inti =1; I <= CNT; ++i) Sum[i] = sum[i-1] +Prime[i]; - } + - intMain () + { A Init (); at intN; - while(SCANF ("%d", &n) = =1&&N) - { - inti =0, ans =0; - for(intj =1; J <= CNT && prime[j] <= N; ++j) - { in inttemp = sum[j]-N; - while(Sum[i] < temp) + +i; to if(Sum[i] = = temp) ans++; + } -printf"%d\n", ans); the } * $ return 0;Panax Notoginseng}code June
UVa 1210 (efficient algorithm design) Sum of consecutive Prime Numbers