日期:2014-05-17  浏览次数:21045 次

C# 小程序之新手练习(四)韩信点兵

     在一千多年前的《孙子算经》中,有这样一道算术题:“今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问物几何?”按照今天的话来说:一个数除以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();
        }
    }
}
明代,数学家程大位用诗歌概括了这一算法,他写道:
           三人同行七十稀,五树梅花廿一枝,
           七子团圆月正半,除百零五便得知。
即:用3除所得的余数乘上70,加上用5除所得余数乘以21,再加上用7除所得的余数乘上15,结果大于105就对105取余即为要求的数。


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();
        }
    }
}