/*
输入一个正整数,若该数能用几个连续正整数之和表示,则输出所有可能的正整数序列
例如:27
2~7
8~10
13~14
或:
100000000
1413~14212
30438~33562
37783~40342
159688~160312
195057~195568
799938~800062
3999988~4000012
19999998~20000002
*/
没有仔细看下面这些代码,先把它们收集起来在慢慢看,一共(5)种方法!
(1).
//折半查找非递归版本
#include <iostream>
using namespace std;
void print(int a, int b)
{
cout<<a<<'~'<<b<<endl;
}
void Search_bin(int s)
{
int sum=1;
int low=1, high=1;
int mid=(s+1)/2 ;
while(high<=mid)
{
while (sum>s)
{
sum-=low;
low++;
if (sum==s)
{
print(low, high);
}
}
high++;
sum+=high;
if (sum==s)
{
print(low, high);
}
}
}
int main()
{
int s;
cin>>s;
Search_bin(s);
system("pause");
}
(2).
#include <stdio.h>
#include <math.h>
void out(int);
void prt(int, int);
int main( )
{
int n;
scanf("%d", &n);
out(n);
}
void out(int n)
{
int max=sqrt(n<<=1);
int x, y, i, j;
for(x=2; x<=max; x++){
if(n%x==0){
y = n/x;
prt(x, y);
if(x!=y)
prt(y, x);
}
}
}
void prt(int x, int y)
{
int i = (x-y+1);
int j = (x+y-1);
if(i<=0 || j<=0 || i&1 || j&1) return;
printf("%d - %d/n", i>>1, j>>1);
}
(3).
1 #include <stdio.h>
2 #include <math.h>
3
4 void out(int);
5 void prt(int, int);
6
7 int main( )
8 {
9 int n;
10 scanf("%d", &n);
11 out(n);
12 }
13
14 void out(int n)
15 {
16 int max=sqrt(n<<=1);
17 int x, y;
18 for(x=2; x<=max; x++){
19 if(n%x==0){
20 y = n/x;
21 prt(x, y);
22 if(x!=y)
23 prt(y, x);
24 }
25 }
26 }
27 void prt(int x, int y)
28 {
29 int i = (x-y+1);
30 int j = (x+y-1);
31 if(i<=0 || j<=0 || i&1 || j&1) return;
32 printf("%d - %d/n", i>>1, j>>1);
33 }
(4).
#include <stdio.h>
int main()
{
int s, n, a, fz;
scanf("%d", &s);
for (n = 2; (fz = (s << 1) - n * (n - 1)) > 0; ++n)
if (fz % (n << 1) == 0 && fz >= (n << 1))
{
a = fz / (n << 1);
printf ("%d~%d/n", a, a + n - 1);
}
return 0;
}
/*
思路是这样的:对于数s,若能表示成以a开头的连续n个整数之和,由等差数列求和公式,不难得出
s = (2a + n - 1) * n
对该式变形,得
a = (2s - n * n + n) / 2n
因此,s能表示成n个连续正整数之和的充要条件是:
上式右端的分母大于0,且能被分子整除,且除得的整数a要大于0。
根据该条件对n进行遍历,从n = 2开始,直到2s - n * n + n小于零结束,对期间的整数检验是否满足
上述条件。
由于2s是定值,所以2s - n * n + n减小速度为n^2级,是比较快速的,故算法的时间复杂度为O(sqrt(s))
----------------------
更正
误:s = (2a + n - 1) * n
正:2s = (2a + n - 1) * n
*/
(5).
#include<stdio.h>
int main(){
int IntNum = 1;
printf("please input a integer:");
scanf("%d",&IntNum);
if(IntNum <= 0){
return 1;
}
for(int i = IntNum - 1 ; i > 0 ; i--){
int temp = i;
int tempTotal = 0;
for(int j = temp ; j > 0 ; j--){
tempTotal += j;
if(tempTotal == IntNum){
//for(int k = temp ; k >= j ; k--){
//printf("%d ",k);
//}
//printf("/n");
printf("%d ~ %d/n",j,temp);
}
else if(tempTotal > IntNum){
break;
}
}
}
return 0;
}
我发现如果长期和他们在一起交流的话,肯定会很快变聪明的!
内容来自 : http://community.csdn.net/Expert/topic/5096/5096433.xml?temp=.3353845
本人整理完毕!