求一個整數分解成連續數字的和
阿新 • • 發佈:2019-01-07
--學習記錄
論壇問題帖:http://bbs.csdn.net/topics/390416116
思路: 設輸入數字為S; 有N個連續整數(N>1),最小整數為M(M>=1),則第二為M+1...第N個則為M+N-1(也可以改設最大數) 通過分解可拆為:S=(1+2+...+N-1)+N*M之和,再利用公式求和即為:(1+(N-1))*(N-1)/2+MN=N*(N-1)/2+MN=S 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("請輸入一個整數:"); string str = Console.ReadLine(); int y = Convert.ToInt32(str); Stopwatch sw1 = new Stopwatch(); sw1.Start(); PrintNum(y); Console.WriteLine("計算時間為:" + sw1.ElapsedMilliseconds.ToString() + "ms"); sw1.Stop(); Console.WriteLine(); Console.ReadLine(); } 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("沒有連續數字的和等於此值"); } } } }