# 求一个整数分解成连续数字的和

--学习记录
论坛问题帖:http://bbs.csdn.net/topics/390416116 思路:

N范围:N(N-1)=2S-2MN-->N平方<2S-2MN-->N<SQRT(2S-2MN)
M范围:M=(2S-N(N-1))/2N
--MSSQL实现--
--支持MASTER..SPT_VALUES 表里面TYPE='P'的最大NUMBER.
CREATE FUNCTION DBO.FN_连续整数和为某值(@SUM INT)
RETURNS TABLE
AS
RETURN
(
SELECT
A.NUMBER AS 连续个数,B.NUMBER AS 起始值,A.NUMBER +B.NUMBER-1 AS 结束值
FROM
MASTER..SPT_VALUES A,MASTER..SPT_VALUES B
WHERE
A.NUMBER BETWEEN 2 AND SQRT (2*@SUM-2) AND A.TYPE='P' AND B.TYPE='P'
AND
B.NUMBER BETWEEN 1 AND CEILING(((2*@SUM*1.00)-A.NUMBER*(A.NUMBER-1))/(2*A.NUMBER))

AND
2*@SUM=A.NUMBER*(A.NUMBER-1)+2*A.NUMBER*B.NUMBER
)


-----C#实现---
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{

Console.WriteLine("请输入一个整数：");
int y = Convert.ToInt32(str);

Stopwatch sw1 = new Stopwatch();
sw1.Start();
PrintNum(y);
Console.WriteLine("计算时间为：" + sw1.ElapsedMilliseconds.ToString() + "ms");
sw1.Stop();
Console.WriteLine();
}

public static int MaxCount(int sum)
{
int n =Convert.ToInt32(Math.Ceiling( System.Math.Sqrt(Convert.ToDouble(sum*2-4))));
return n;
}

public static void PrintNum(int sum)
{
string str = "";
int n=MaxCount(sum);
int tempj = 0, tempi = 0;
for (int i = 2; i < n; i++)
{
int m = Convert.ToInt32(System.Math.Ceiling((Convert.ToDouble(2*sum)-i*(i-1)) / (2*i)));
for (int j = 1; j <= m; j++)
{
if (i * (i - 1) + 2 * i*j == 2 * sum)
{
tempj = j;
tempi = i;
str = "";
}
}
if (tempj > 0)
{
str = "";
for (int k = tempj; k < tempj + i; k++)
{
str = str + k.ToString() + "+";
}
Console.WriteLine(tempi.ToString() + "个数:" + str.TrimEnd( '+') + "=" + sum.ToString());
}
tempj = 0; tempi = 0;
}
if (string.IsNullOrEmpty(str))
{
Console.WriteLine("没有连续数字的和等于此值");
}
}

}

}



07-11 3473

10-13 2982
10-05 4091
09-24 7024
08-26 309
05-24 2914
11-15 4065
05-22 531
11-18 3468
11-19 962
03-30 1275
04-13 1497
06-14 6255