思路:就是把gcd拆一下,因为如果GCD可以,这些数就也可以
3,6
gcd = n = 3
1/3 没了,0 += 2
GCD辗转相除法:b一开始是除数,后来是余数。余数为0就行了
16 4
4,4
4,0
所以返回a = 4
https://www.geeksforgeeks.org/common-divisors-of-two-numbers/
// Java implementation of program class Test { // method to calculate gcd of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // method to calculate all common divisors // of two given numbers // a, b --> input integer numbers static int commDiv(int a, int b) { // find gcd of a, b int n = gcd(a, b); // Count divisors of n. int result = 0; for (int i = 1; i <= Math.sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) result += 1; else result += 2; } } return result; } // Driver method public static void main(String args[]) { int a = 12, b = 24; System.out.println(commDiv(a, b)); } }