poj2793 Sum of Consecutive Prime Numbers(尺取法)

tech2023-11-02  107

#include<iostream> #include<algorithm> #include<cstring> #include<vector> #include<set> #include<stack> #include<map> #include<cmath> using namespace std; const int N = 10003, inf = 0x3f3f3f3f; typedef pair<int, int> PIR; typedef long long ll; int prime[N], cnt; bool vis[N]; void get_prime(int n) { for (int i = 2; i <= n; i++) { if (!vis[i]) prime[cnt++] = i; for (int j = 0; prime[j] <= n / i; j++) { vis[prime[j] * i] = true; if (i % prime[j] == 0)//prime[j]一定是i的最小质因子,保证了每个合数只会被它的最小质因子筛掉 break; } } } int main() { get_prime(N); int n; while (cin >> n&& n) { int l = 0, r = 0, sum = prime[l]; int res = 0; while (l <= r&&prime[l]<=n) { if (sum == n) res++; if (sum < n) sum += prime[++r]; else sum -= prime[l++]; } cout << res << endl; } return 0; }

 

最新回复(0)