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

来源:互联网 发布:金属软件 编辑:程序博客网 时间:2024/05/15 21:39

--学习记录

论坛问题帖: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=SN范围: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 TABLEASRETURN( 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("没有连续数字的和等于此值");            }        }    }    }



 

原创粉丝点击