zoukankan      html  css  js  c++  java
  • 算法分析求最大公约数 gcd(int x,int y) (greatest common divisor )

    package chapter5;
    import java.util.Scanner;
    public class Gcd {

     /**
      * 计算2个数的最大公约数
      */
     public static void main(String[] args) {
      
        int x;
        int y;
        int result;
        System.out.println("please in put the x:");
        Scanner input=new Scanner(System.in);
        x=input.nextInt();
        System.out.println("please in put the y:");
        Scanner input1=new Scanner(System.in);
        y=input1.nextInt();
        result=gcd(x,y);
        System.out.println(x+"和"+y+"的最大公约数为:"+result);
     }


      /*
       * 方法1: The “brute force” approach
       * /  
          private static int gcd(int x, int y) {
            int guess = Math.min(x, y);
              while (x % guess != 0 || y % guess != 0) {
                            guess--;
                     }
              return guess;
            }
       

      
     /*
      *  方法2:
      *  Euclid’s algorithm 欧几里德算法:
      *  1. Divide x by y and compute the remainder; call that remainder r.
      *  2. If r is zero, the procedure is complete, and the answer is y.
      *  3. If r is not zero, set x equal to the old value of y, set y equal to r, and repeat the entire
      */
       private static int gcd(int x, int y) {
          int r = x % y;
            while (r != 0) {
                x = y;
                y = r;
                r = x % y;
            }
            return y;
       }
    }

    -----------------------------------------------------------------------

    输入2个比较大的数字: 1,000,005 and 1,000,000  来验证2个方法实现的好坏:

    分析:

    1. 方法1 : the brute-force algorithm requires a million steps;

    2. 方法2: Euclid’s algorithm requires only two steps;

    结论:

      方法2 比 方法1 算法优化很多

    不断的总结,才能不断的提高;不断的思考,才能不断的进步!
  • 相关阅读:
    redis client 2.0.0 pipeline 的list的rpop bug
    Python解释器镜像源修改
    全连接层
    测试(张量)- 实战
    数据加载
    Python之微信-微信好友头像合成
    高阶操作
    MYSQL 查询缓存
    SQL Server 查看指定表上的索引
    MYSQL 查看表上索引的 1 方法
  • 原文地址:https://www.cnblogs.com/nzyjlr/p/2003413.html
Copyright © 2011-2022 走看看