ABC142-D: Disjoint Set of Common Divisors
問題
解説
正整数
このとき,
よって, 各素因数について1つずつだけ選ぶことができるので答えは最大公約数の素因数の個数 + 1 となる.
1 は素数ではないが
計算量は
実装例
C++
cpp
#include <iostream>
#include <map>
std::map<long long, int> prime_factor(long long n) {
std::map<long long, int> res;
for (long long x = 2; x * x <= n; x++) {
while (n % x == 0) {
++res[x];
n /= x;
}
}
if (n != 1) {
res[n] = 1;
}
return res;
}
long long gcd(long long x, long long y) {
while (y != 0) {
long long r = x % y;
x = y;
y = r;
}
return x;
}
int main() {
long long A, B;
std::cin >> A >> B;
long long g = gcd(A, B);
std::map<long long, int> prime_factors = prime_factor(g);
std::cout << prime_factors.size() + 1 << "\n";
return 0;
}
Python
python
#!/usr/bin/env python3
def prime_factor(n):
res, x = {}, 2
while x * x <= n:
while n % x == 0:
res[x] = res.get(x, 0) + 1
n //= x
x += 1
if n != 1:
res[n] = 1
return res
def gcd(x, y):
while y != 0:
x, y = y, x % y
return x
A, B = map(int, input().split())
g = gcd(A, B)
prime_factors = prime_factor(g)
print(len(prime_factors) + 1)