比较好用的是辗转相除法,
求最大公约数辗转相除法
。比如:49和91
a b temp
49 % 91 = 49
91 % 49 = 42
49 % 42 = 7
42 % 7 = 0
所以最大公约数就是7.
public class T {
public static void main(String[] args) {
int gcd = gcd(91, 49);
System.out.println(gcd);
}
/**
* greatest commond divisor
* @param a
* @param b
* @return
*/
public static int gcd(int a, int b) {
while(b != 0) {
int temp = a%b;
a = b;
b = temp;
}
return a;
}
}