一个老的程序设计题(出处:百度之星编程大赛)

来源:互联网 发布:长城宽带 封端口 编辑:程序博客网 时间:2024/05/18 11:25

 题目描述:一个正整数有可能可以被表示为n(n>=2)个连续正整数之和,如:
    15=1+2+3+4+5
    15=4+5+6
    15=7+8
    请编写程序,根据输入的任何一个正整数,找出符合这种要求的所有连续正整数序列
。    输入数据:一个正整数,以命令行参数的形式提供给程序。   输出数据:在标准输
出上打印出符合题目描述的全部正整数序列,每行一个序列,每个序列都从该序列的最小
正整数开始、以从小到大的顺序打印。如果结果有多个序列,按各序列的最小正整数的大
小从小到大打印各序列。此外,序列不允许重复,序列内的整数用一个空格分隔。如果没
有符合要求的序列,输出“NONE”。   
例如,对于15,其输出结果是:
    1 2 3 4 5
    4 5 6
    7 8  
 对于16,其输出结果是:    NONE

 

#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>

using namespace std;

bool IsNotNumber( char c )
{
 if( c < 0x30 || c > 0x39 )
  return false;
 return true;
}

bool Compute( int num )
{
 bool sym = false;
 double x1,d1,d2;
 int count = num/2+1;
 for( int i = 1; i <= count; i++ )
 {
  x1 = ( ( 1 - 2.0*(double)i ) + sqrt( (2.0*(double)i-1.0)*(2.0*(double)i-1.0)+8*(double)num ) )/2.0;
  if( x1 > 0 )
  {
   d2 = modf( x1, &d1 );
   if( d2  < 0.0000001 )
   {
    for( int j = 0; j < (int)x1; j++ )
     cout << i+j <<" ";
    cout << endl;
    cout << endl;
    sym = true;
   }    
  }
 }
 return sym;
}

int main( int argc, char **argv )
{
 string word;
 string num("0123456789");
 while( getline( cin, word ), word != "/n" )
 {
  string::iterator iter = find_if( word.begin(), word.end(), &IsNotNumber );
  if( iter == word.end() )
  {
   cerr << "Input error. Please input again!" << endl;
  }
  else
  {
   int num = atoi( word.c_str() );
   if( !Compute( num ) )
    cout << "None."<<endl;
  }
 }
 
 system("Pause");
 return 0;
}

// 计算之前先进行了一下处理,可能会快一些吧

//请诸位点评一下,谢谢 

原创粉丝点击