H 正整数的连加分解(黄)
Time Limit:1000MS Memory Limit:65536K
Total Submit:41 Accepted:2
Description
有一天树人计算机学校的老师给他的学生们出了一道简单程序设计作业题,写出一个整数分解成连加的形式的所有情况。
比如整数为15 ,可以变成 15 = 1 + 2 + 3 + 4 + 5;也可以写成 15 = 7 + 8 ;还可以写成15 = 4 + 5 + 6 ;
(即把一个整数写成一段连续整数的和的形式。)
假如你就是学生之一,现在你该如何解决呢?发挥你的聪明才智吧……
Input
正整数N(1 < N <= 100000),包含多组测试数据,以0结束.
Output
对应N分解成连加的形式的所有情况 , 首先输出N ,考虑同一个数有多种这样的组合,每种情况用case i:表示 ,输出首数字和尾数字 ,
如15 = 1 + 2 + 3 + 4 + 5 输出 case 1: 1 5
15 = 4 + 5 + 6 输出 case 2: 4 6
15 = 7 + 8 输出 case 3: 7 8
每种情况占一行.
当N不能被分解时输出 can not analyze ! 。
Sample Input
15 2 55 66 0
Sample Output
15 case1:1 5 case2:4 6 case3:7 8 2 can not analyze! 55 case1:1 10 case2:9 13 case3:27 28 66 case1:1 11 case2:15 18 case3:21 23
#include <iostream> #include <fstream> #include <cmath> using namespace std; int Str2numToInteger(char *mystr)//???????????????????????????????? { long double num=0; int i=-1; int pass; double index=0; while(mystr[++i]!=0) if(mystr[i]>='0'&&mystr[i]<='9') { num=num*10+mystr[i]-'0'; } else { if(mystr[i]=='.') pass=i; index=strlen(mystr)-1-pass; } return num/pow(10.0,index); } void InData(int &n)//n???????????? { ofstream outfile("ttt.txt"); //int i; int tempnum; while(1) { cin>>tempnum; if(tempnum==0) return; outfile<<tempnum<<endl; n++; } outfile.close(); } int dealdata(char *tempstr) { int caseN=1; //ifstream outfile("ttt.txt"); //char tempstr[10]; //outfile>>tempstr; int dealnum = Str2numToInteger(tempstr); int Left=0,Right=0; int i;//=1; int balance;//= i; int processN; int judgeBe=0; for(balance=1;balance<dealnum;balance++) { processN = dealnum; Left = balance; i = balance; bool judge=0; while(1) { //dealnum = dealnum-i; processN = processN - i; if(processN==0){ Right=i; judge=1; break;}// else if(processN<0) break;//???????????????????????? i++; } if(judge==1)//???????????? { cout<<"case"<<caseN<<":"<<Left<<" "<<Right<<endl; caseN++; judgeBe=1; } } return judgeBe; } int main() { int n; //cin>>n; InData(n); ifstream infile("ttt.txt"); char tempstr[10]; while(infile.getline(tempstr,10)) { cout<<tempstr<<endl;//?????????????????????????? if(dealdata(tempstr)==0) cout<<"can not analyze!"<<endl; } infile.close(); }