算法分析---求最大公约数 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个方法实现的好坏:

2011040215273243.jpg

分析:

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

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

结论:

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

转载于:https://www.cnblogs.com/nzyjlr/archive/2011/04/02/2003413.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值