如题:求连续正整数使得其和为给定的一个正整数下面给出我的解法,几乎可以一步到位求出来
实现代码如下:
/**
*Author: Koth (http://weibo.com/yovn)
*Date: 2011-12-01
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
int solve(int Y,int& X){
int m=0;
int t=Y;
if(Y<=0){
X=Y;
return 1;
}
while((t&1)==0){
m+=1;
t=t>>1;
}
if(m==32){
X=Y;
return 1;
}
int lastK=32;
for(;lastK>m+1;lastK--){
if(Y &(1<<(lastK-1))){
break;
}
}
//its a number st. exp(2,K)
if(lastK==(m+1)){
X=Y;
return 1;
}
int k=1<<(m+1);
int b=(Y>>m)-(1<<(lastK-m-1));
X=(1<<(lastK-m-2))+(b+1-k)/2;
if(X<=0){
k=k-1-((0-X)<<1);
X=0-X+1;
}
return k;
}
int main(int argc,char* argv[]){
if(argc<=1){
fprintf(stdout,"Usage:%s number\n",argv[0]);
return 0;
}
int Y=atoi(argv[1]);
int X=0;
int k=solve(Y,X);
fprintf(stdout,"%d=",Y);
for(int i=0;i<k;i++){
fprintf(stdout,"%d",X+i);
if(i<(k-1)){
fprintf(stdout,"+");
}
}
fprintf(stdout,"\n");
return 0;
}