问题描述:
求任意两个数的最大公约数。
public class Main {
public static void main(String[]Args){
System.out.println(gcd(8,4)); //测试数 8 和 4
}
public static int gcd(int a,int b){ //辗转相除 (欧几里德算法)
int temp; //设置中间变量
if(a<b){
temp = a;
a=b;
b=temp;
}
while(b!=0){ //通过循环求两数的余数直到为0
temp = a%b;
a=b;
b=temp;
}
return a; //返回最大公约数
}
}
public class Main {
public static void main(String[]Args){
System.out.println(gcd(12,6)); //测试数 12 和 6
}
public static int gcd(int a,int b){ //辗转相除法
if(a%b==0){
return b;
}
else{
return gcd(b,a%b); //递归调用形式
}
}
}