Java Common Prime Divisors
public class Solution {
public static int commonPrimeDivisors(int[] a, int[] b) {
int counter = 0;
for (int i = 0; i < a.length; i++) {
int x = a[i];
int y = b[i];
int d = gcd(x, y);
x = removeCommonPrimeDivisors(x, d);
if (x != 1) {
continue;
}
y = removeCommonPrimeDivisors(y, d);
if (y == 1) {
counter++;
}
}
return counter;
}
private static int gcd(int n, int m) {
if (n % m == 0) {
return m;
}
return gcd(m, n % m);
}
private static int removeCommonPrimeDivisors(int n, int m) {
while (n != 1) {
int d = gcd(n, m);
if (d == 1) {
break;
}
n /= d;
}
return n;
}
}
This checks whether two numbers are built from the same prime factors by repeatedly dividing out their shared parts.