C++ Common Prime Divisors
#include <cstddef>
#include <vector>
long long commonPrimeDivisorsGcd(long long n, long long m)
{
if (n % m == 0) {
return m;
}
return commonPrimeDivisorsGcd(m, n % m);
}
long long removeCommonPrimeDivisors(long long n, long long m)
{
while (n != 1) {
long long d = commonPrimeDivisorsGcd(n, m);
if (d == 1) {
break;
}
n /= d;
}
return n;
}
int commonPrimeDivisors(const std::vector<int>& a, const std::vector<int>& b)
{
int counter = 0;
for (std::size_t i = 0; i < a.size(); ++i) {
long long x = a[i];
long long y = b[i];
long long d = commonPrimeDivisorsGcd(x, y);
x = removeCommonPrimeDivisors(x, d);
if (x != 1) {
continue;
}
y = removeCommonPrimeDivisors(y, d);
if (y == 1) {
++counter;
}
}
return counter;
}
This checks whether two numbers are built from the same prime factors by repeatedly dividing out their shared parts.