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 算法优化很多

    不断的总结,才能不断的提高;不断的思考,才能不断的进步!
  • 相关阅读:
    ThinkPHP5.0更改框架的验证方法:对象->validate(true)->save();
    ThinkPHP5.0版本和ThinkPHP3.2版本的区别
    ThinkPHP5.0版本的优势在于:
    11: django-haystack+jieba+whoosh实现全文检索
    10: supervisor进程管理工具
    09: redis集群之sentinel
    08: python支付宝支付
    07: redis分布式锁解决超卖问题
    06:keepalive高可用集群(新)
    05: 使用docker部署nginx负载均衡
  • 原文地址:https://www.cnblogs.com/nzyjlr/p/2003413.html
Copyright © 2011-2022 走看看