用java写的关于求最大公约数的三种方法:
package suda.alex.chapter2;
import java.util.*;
public class Gcd {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.println("please input two numbers:");
// int x = scanner.nextInt();
// int y = scanner.nextInt();
Long x = scanner.nextLong();
Long y = scanner.nextLong();
// System.out.println("result:"+gcd1(x, y));
// System.out.println("result:"+gcd2(x, y));
System.out.println("result:"+gcd3(x, y));
}
public static int gcd1(int x, int y){
return (y==0)?x:gcd1(y,x%y);
}
public static Long gcd2(Long x,Long y){
if(x < y){
return gcd2(y,x);
}
else if(y == 0){
return x;
}
else{
return gcd2(x-y,y);
}
}
public static Long gcd3(Long x, Long y){
if(x < y){
return gcd2(y,x);
}
else if(y == 0){
return x;
}
else{
if(x%2 == 0){
if(y%2 == 0)
return (gcd2(x>>1,y>>1)<<1);
else
return gcd2(x>>1,y);
}
else{
if(y%2 == 0)
return gcd2(x,y>>1);
else
return gcd2(y,x-y);
}
}
}
}