求最大公约数----辗转相除法
一般写法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public class Main {
public static void main(String[] args) {
System.out.println(gcd(18, 2));
}
private static int gcd(int a, int b) {
// TODO Auto-generated method stub
while (b != 0) {
int c = a % b;
a = b;
b = c;
}
return a;
}
}
递归实现
1
2
3
4
5
6
7
8
9
10
11
12
13public class Main {
public static void main(String[] args) {
System.out.println(gcd(18, 2));
}
private static int gcd(int a, int b) {
// TODO Auto-generated method stub
if (b == 0) {
return a;
}
return gcd(b, a%b);
}
}