import java.util.Scanner;
public class Gcd {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
System.out.println(Gcd1(m, n));
System.out.println(Gcd2(m, n));
System.out.println(Gcd3(m, n));
}
public static int Gcd1(int m, int n) {
int t = m > n ? n : m;
if (m == 0) {
return n;
}
if (n == 0) {
return m;
}
// while (m % t || n % t) {这个代码在c或c++中是可用的
while (m % t != 0 || n % t != 0) {
t--;
}
return t;
}
// 欧几里得的辗转相除法 迭代法
public static int Gcd2(int m, int n) {
if (m == 0) {
return n;
}
if (n == 0) {
return m;
}
if (m < n) {
m = m + n;
n = m - n;
m = m - n;
}
while ((m = m % n) != 0) {
m = m + n;
n = m - n;
m = m - n;
}
return n;
}
// 使用尾递归的方法来求最大公约数
public static int Gcd3(int m, int n) {
if (m == 0) {
return n;
}
if (n == 0) {
return m;
}
if (m < n) {
m = m + n;
n = m - n;
m = m - n;
}
if (m % n == 0)
return n;
else
return Gcd3(n, m % n);
}}
参考答案:
计算两个非负整数m,n的最大公约数,若m==0,则返回n的值。否则,将n%m 得到余数i,m,n的最大公约数就是i,m的最大公约数
// 参考答案
public static int Gcd(int m, int n) {
if (m == 0) {
return n;
} else {
int i = n % m;
return Gcd(i, m);
}
}