算法分析---求最大公约数 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 算法优化很多