本来写算法的,碰到了N年未遇到的数学问题,欧几里得辗转相除法求最大公约数
举个例子吧,原理说了费劲
120 42之间的GCD
120 % 42 = 36
接下来进行
42 % 36 = 6
接下来
36 % 6 = 0
那么结果出来了,最后一个可以整除的除数就是结果
代码如下
public class Solution {
/**
* @param a: the given number
* @param b: another number
* @return: the greatest common divisor of two numbers
*/
public int gcd(int a, int b) {
// write your code here
while(a % b != 0){
int tmp = a;
a = b;
b = tmp % b;
}
return b;
}
}
网友评论