Sum of Consecutive Prime Numbers POJ - 2739(線性尤拉篩+尺取法)
題意:
一些正整數可以由一個或多個連續質數的總和表示。給定一個的正整數n,問滿足條件的有多少種情況?
題目:
Some positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has three representations 2+3+5+7+11+13, 11+13+17, and 41. The integer 3 has only one representation, which is 3. The integer 20 has no such representations. Note that summands must be consecutive prime
numbers, so neither 7 + 13 nor 3 + 5 + 5 + 7 is a valid representation for the integer 20.
Your mission is to write a program that reports the number of representations for the given positive integer.
Input
The input is a sequence of positive integers each in a separate line. The integers are between 2 and 10 000, inclusive. The end of the input is indicated by a zero.
Output
The output should be composed of lines each corresponding to an input line except the last zero. An output line includes the number of representations for the input integer as the sum of one or more consecutive prime numbers. No other characters should be inserted in the output.
Sample Input
2
3
17
41
20
666
12
53
0
Sample Output
1
1
2
3
0
0
1
2
分析:
1.將 2 至 10000 內的素數存入一個陣列;
2.對於每一個給定的數,從左向右遍歷陣列,根據連續素數的和的大小不斷的增減元素,直到找到一個個解。
AC模板:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int M=1e4+10;
int n,k,r,l,ans,mi;
int dp[M],book[M];
void init()
{
k=0;
/** for(int i=2; i<M; i++)
{
if(!book[i])
{
dp[k++]=i;
for(int j=i*2; j<M; j+=i)
book[j]=1;
}
}*/
for(int i=2;i<M;i++)
{
if(!book[i])
dp[k++]=i;
for(int j=0;j<k&&i*dp[j]<M;j++)
{
book[i*dp[j]]=1;
if(i%dp[j]==0)break;
}
}
}
int solve(int x)
{
ans=0;
for(int i=0; i<k&&dp[i]<=x; i++)
{
l=i,mi=0;
while(mi<x&&l<k)
{
mi+=dp[l++];
}
if(mi==x)
ans++;
}
return ans;
}
int main()
{
init();
while(~scanf("%d",&n)&&n)
{
printf("%d\n",solve(n));
}
return 0;
}
備戰ccpc分站賽ing ,題目分析簡略,見諒,轉載請註明出處。。。。。
相關文章
- 尤拉篩(線性篩)
- 829. Consecutive Numbers Sum
- 尤拉篩線性篩質數
- 尤拉篩
- Prime Path(POJ - 3126)【BFS+篩素數】
- 素數篩(埃氏篩法與尤拉篩)
- 素數個數 <埃式篩 && 尤拉篩>
- Leetcode 967 Numbers With Same Consecutive DifferencesLeetCode
- 【演算法學習】尺取法演算法
- 信奧日記——數論(快速冪、埃氏篩、尤拉篩)
- POJ3126-Prime Path
- ACM-ICPC 2018 南京賽區網路預賽__J. Sum【尤拉篩法+質因子分解+思維】ACM
- 尤拉函式性質和模版函式
- 尤拉計劃700:尤拉幣
- Sum of Square Numbers 平方數之和
- 129-Sum Root to Leaf Numbers
- 洛谷P1712 [NOI2016]區間 尺取法+線段樹+離散化
- 素數篩 : Eratosthenes 篩法, 線性篩法
- LeetCode 129. Sum Root to Leaf NumbersLeetCode
- 尤拉素數篩選與命令列傳參啟動C程式命令列C程式
- 尤拉方程
- 尤拉定理
- 線性篩合數
- POJ 2230 Watchcow 尤拉回路
- POJ3252Round Numbers(數位dp)
- LeetCode之Sum of Even Numbers After Queries(Kotlin)LeetCodeKotlin
- 尤拉函式φ函式
- 尤拉路徑
- 尤拉降冪
- Diff-prime Pairs(思維+素數篩)AI
- 尤拉計劃701:隨機連線區域隨機
- 尤拉公式 - 筆記公式筆記
- 【圖論】尤拉圖圖論
- POJ-3061 Subsequence(字首和+二分/尺取)
- 尤拉序的小技巧
- 淺談尤拉函式函式
- 尤拉計劃622:洗牌
- 尤拉函式入門函式