Sum of Consecutive Prime Numbers
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 26954 Accepted: 14544Description 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
Source Japan 2005
这道题数据较小, 所以判断素数用了很朴素的方法, 追求效率可以用筛法.
求解的过程直接套上两个循环, 数据较小, 时间复杂度完全OK
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int n)
{
for ( int i=2; i<=sqrt(n); ++i ) {
if( n%i ==0 ) return false;
}
return true;
}
int main( )
{
int prime[1250] = {2}, cnt = 0;
for ( int i = 3; i<= 10000; ++i ) {
if( isPrime(i) ) prime[++cnt] = i;
}
int n;
while( cin >> n && n ) {
int k = 0;
bool flag = 1;
while( prime[k++] <= n ) {
int sum = 0;
for( int i = k-1; sum < n; ++i ) {
sum += prime[i];
if( sum == n ) {
flag = 0;
cout << n << " = " << prime[k-1];
for ( int j = k; j<=i; ++j ) {
cout << " + " << prime[j];
}
cout << endl;
}
}
}
if( flag ) cout << "no!" << endl;
}
}
写出这个代码之前纠结了时间复杂度问题, 觉得这样判定会很慢(事实证明当时我错了), 所以奇思妙想了一个打出所有可能是连续素数和的数, 可是这种方法是能判定是不是, 而不能给出表达式.
#include <iostream>
#include <cmath>
#include <set>
using namespace std;
bool isPrime(int n)
{
for(int i=2; i<=sqrt(n); ++i) {
if( n%i ==0 ) return false;
}
return true;
}
int main( )
{
int prime[1250] = {2}, p = 0;
for ( int i=3; i<=1000; ++i ) {
if(isPrime(i)) prime[++p] = i;
}
cout << "p = " << p << endl;
++p;
set<int>ss;
int add[1250] = {};
for( int i = 1; i <= p; ++i ) {
for( int j=1; j <= p+1-i; ++j ) {
add[j] = add[j] + prime[j+i-2];
cout << add[j] << ' ';
ss.insert(add[j]);
}
cout << endl;
}
set<int>::iterator it = ss.begin();
while( it != ss.end() ) {
cout << *it << endl;
it++;
}
int n;
while(cin >> n) {
if( ss.find(n) != ss.end() ) cout << "yes\n";
else cout << "no\n";
}
}
敬天赋异禀的我!