• 韩信点兵问题的简单算法(downmoon)


    在园子里有朋友问起这个问题:
    爱因斯坦曾出过这样一道有趣的数学题,有一个长阶梯,每步上2阶,最后剩1阶;若每步上3阶,最后剩2阶,若每步上5阶,后剩4阶;若每步上6阶,最后剩5阶;只有每步上7阶,最后一阶也不剩。问至少有多少阶阶梯?编写一个JAVA程序,解决该问题。

    这个是我国古代的韩信点兵问题:古人用剩余定理口算或心算,我们现在有计算机了,算法很简单:

    我以C#为例,Java非常类似。JAVA

    public static void main(String[] args) {
             
    int x;
                
    for (x = 0; x < 200; x++)
                {
                    
    if (x % 2 == 1 && x % 3 == 2 && x % 5 == 4 && x % 6 == 5 && x % 7 == 0)
                    {
                        System.out.print(
    "这个数字是:" +x);
                    }
                }
        }


    说明:因为要取最小数,所以先设最大值100,无解,再设为200,得119
    C#:

    Code

    后来有朋友提起是7的倍数,
    于是再优化下:

     static void Main(string[] args)
            
    {
                
    int x;
                
    for (x = 0; x < 200= x + 7)
                
    {
                    
    if (x % 2 == 1 && x % 3 == 2 && x % 5 == 4 && x % 6 == 5)
                    
    {
                        Console.WriteLine(
    "这个数字是:" + x.ToString());
                    }

                }

                Console.ReadKey();
            }


    再考虑是奇数,更加简洁:

    static void Main(string[] args)
            
    {

                
    int x;
                
    for (= 7; x < 200= x + 14)
                
    {
                    
    if ( x % 3 == 2 && x % 5 == 4 && x % 6 == 5)
                    
    {
                        Console.WriteLine(
    "这个数字是:" + x.ToString());
                    }

                }

                Console.ReadKey();
            }




    cncxz(虫虫)
    台阶阶梯总数加一是为2、3、5、6的最小公倍数,而且是7的倍数,所以定是30的倍数减1,可得如下算法:

     1 static void Main(string[] args)  
     2         {  
     3             int x;  
     4             for (int i = 1; i < 10; i++)  
     5             {  
     6                 if ((* 30 - 1% 7 == 0)  
     7                 {  
     8                     x = (i * 30 - 1);  
     9                     Console.WriteLine("这个数字是:" + x.ToString());  
    10                 }  
    11             }  
    12             Console.ReadKey();  
    13         } 
    邀月注:本文版权由邀月和博客园共同所有,转载请注明出处。
    助人等于自助!  3w@live.cn
  • 相关阅读:
    在Salesforce中实现对Object的增删改查操作
    在Salesforce中通过编写C#程序调用dataloadercliq的bat文件取触发调用data loader来批量处理数据
    在Salesforce中通过dataloadercliq调用data loader来批量处理数据
    【LeetCode】189. Rotate Array
    【LeetCode】190. Reverse Bits
    【LeetCode】191. Number of 1 Bits
    【C++】不要想当然使用resize
    【LeetCode】174. Dungeon Game
    【LeetCode】Largest Number
    【DeepLearning】Exercise:Convolution and Pooling
  • 原文地址:https://www.cnblogs.com/downmoon/p/1567443.html
Copyright © 2020-2023  润新知