用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);
}
}
}
}
本文介绍使用Java语言实现求两个整数的最大公约数的三种不同方法,包括递归、迭代和位操作技巧。
2213

被折叠的 条评论
为什么被折叠?



