日期:2014-05-17 浏览次数:21258 次
在一千多年前的《孙子算经》中,有这样一道算术题:“今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问物几何?”按照今天的话来说:一个数除以3余2,除以5余3,除以7余2,求这个数。这样的问题,也有人称为“韩信点兵”.它形成了一类问题,也就是初等数论中的解同余式。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
    class Program
    {
        /// <summary>
        /// 韩信点兵(一)枚举法
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Console.WriteLine("今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问物几何?");
            int a = 0, b = 0, c = 0;
            for (int i = 1; i <= 100; i++)//枚举1到100的每个数,找出最小的符合条件的
            {
                Math.DivRem(i, 3, out a);
                Math.DivRem(i, 5, out b);
                Math.DivRem(i, 7, out c);
                if (a == 2 && b == 3 && c == 2)
                {
                    Console.WriteLine("共有士兵{0}人",i);
                    break;
                }
            }
            Console.ReadLine();
        }
    }
}明代,数学家程大位用诗歌概括了这一算法,他写道:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
    class Program
    {
        /// <summary>
        /// 韩信点兵(二)公式法
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Console.WriteLine("今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问物几何?");
            int a = 2, b = 3, c = 2;
            int num = (70 * a + 21 * b + 15 * c) > 105 ? (70 * a + 21 * b + 15 * c) % 105 : (70 * a + 21 * b + 15 * c);//根据公式计算
            Console.WriteLine("共有士兵{0}人",num);
            Console.ReadLine();
        }
    }
}