POJ2739 Sum of Consecutive Prime Numbers 确定某个数以内的所有素数

参考:https://www.cnblogs.com/baozou/articles/4481191.html

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 const int N=1e4+10;
 6 bool prime[N];
 7 void primemap()
 8 {
 9     memset(prime,true,sizeof(prime));
10     prime[0]=prime[1]=false;
11     for (int i=2;i<N;i++)
12     {
13         if (prime[i])
14         {
15             for (int j=2*i;j<N;j+=i)
16             {
17                 prime[j]=false;
18             }
19         }
20     }
21 }
22 int solve(int x)
23 {
24     int ans=0;
25     for (int i=2;i<=x;i++)
26     {
27         if (prime[i])//遍历以素数开头的和,所以要先判断!
28         {
29             int sum=0;
30             for (int j=i;j<=x;j++)
31             {
32                 if (prime[j])
33                 {
34                     sum+=j;
35                 }
36                 if (sum==x)
37                 {
38                     ans++;
39                     break;
40                 }
41                 if (sum>x)
42                 {
43                     break;
44                 }
45             }
46         }
47     }
48     return ans;
49 }
50 int main()
51 {
52     int in;
53     primemap();
54     while (cin>>in&&in)
55     {
56         cout<<solve(in)<<endl;
57     }
58 
59     return 0;
60 }

猜你喜欢

转载自www.cnblogs.com/hemeiwolong/p/9398018.html