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

    不断的总结,才能不断的提高;不断的思考,才能不断的进步!
  • 相关阅读:
    《大话设计模式》的一些总结
    一个仿jdkd的动态代理
    一道笔试题(构造数组)
    c# 汉字转拼音
    IDEA常用插件盘点(香~~)
    服务器概念、应用服务器盘点大科普
    创建一个简单的Struts 2程序
    JAVA(Object类、Date类、Dateformat类、Calendar类)
    DQL查询语句和约束
    MySQL操作语句
  • 原文地址:https://www.cnblogs.com/nzyjlr/p/2003413.html
Copyright © 2011-2022 走看看