首页 > 代码库 > (数学+尺取法)2739 - Sum of Consecutive Prime Numbers

(数学+尺取法)2739 - Sum of Consecutive Prime Numbers

原题链接:http://poj.org/problem?id=2739


题意:问一个数有几种方法用连续的素数和表示。


分析:其实就是很简单,先打表,然后对prime数组跑一波尺取法,如果==n就ans++。


代码:

 1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cmath> 5 #include <cstring> 6 #include <set> 7 #include <vector> 8 #include <queue> 9 #include <map>10 #include <list>11 #include <bitset>12 #include <string>13 #include <cctype>14 #include <cstdlib>15 16 using namespace std;17 18 typedef long long ll;19 typedef unsigned long long ull;20 21 22 const int inf = 1<<30;23 const ll lnf = 1ll<<60;24 25 //--------------------------26 27 const int maxn=10010;28 int prime[maxn];29 bool vis[maxn];30 31 int Euler_prime() {32     memset(vis, true, sizeof(vis));33     int tot = 0;34     for (int i = 2; i < maxn; i++) {35         if (vis[i]) prime[tot++] = i;36         for (int j = 0; j < tot&&prime[j] * i < maxn; j++) {37             vis[i*prime[j]] = false;38             if (i%prime[j] == 0) break;39         }40     }41     return tot;42 }43 44 45 void solve() {46     int n;47     int pn=Euler_prime();48     while(~scanf("%d",&n)&&n){49         int ans=0;50         int l=0,r=0;51         int res=0;52         while(r<pn){53             while(res<n){54                 res+=prime[r];55                 r++;56                 if(r>=pn)break;57             }58             while(res>=n){59                 if(res==n)ans++;60                 res-=prime[l];61                 l++;62             }63         }64         printf("%d\n",ans);65     }66 }67 68 69 70 int main() {71 72 #ifndef ONLINE_JUDGE73     freopen("in.txt", "r", stdin);74     //freopen("out.txt", "w", stdout);75 #endif76     //iostream::sync_with_stdio(false);77     solve();78     return 0;79 }

 

(数学+尺取法)2739 - Sum of Consecutive Prime Numbers