Leetcode Problem 2427: Number of Common Factors
Given two positive integers a
and b
, return the number of common factors of a
and b
.
A factor of an integer n
is defined as a positive integer i
such that n % i == 0
.
a
and b
?
a
and b
guaranteed to be positive?
a
and b
is the same as the number of factors of gcd(a, b)
. This simplifies the problem significantly, as finding the factors of a smaller number (the GCD) is easier.i
is a factor, then gcd(a, b) / i
is also a factor.O(log(min(a, b)))
time using the Euclidean algorithm.n
involves iterating up to sqrt(n)
, which is O(sqrt(n))
.Overall, the time complexity should be efficient for large inputs.
import math
def common_factors(a: int, b: int) -> int:
def gcd(x, y):
while y:
x, y = y, x % y
return x
def count_factors(n):
count = 0
for i in range(1, int(math.sqrt(n)) + 1):
if n % i == 0:
count += 1
if i != n // i:
count += 1
return count
gcd_value = gcd(a, b)
return count_factors(gcd_value)
# Example usage
print(common_factors(12, 15)) # Output: 2, because common factors are 1 and 3
print(common_factors(100, 10)) # Output: 4, because common factors are 1, 2, 5, and 10
gcd
to compute the greatest common divisor of two integers using the Euclidean algorithm.count_factors
to count all the factors of a given integer n by iterating up to the square root of n and checking if each integer is a factor.a
and b
.count_factors
to count the number of factors of the gcd.This solution efficiently combines GCD computation with factor counting for an optimal approach.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?