Solving Leetcode Interviews in Seconds with AI: Number of Common Factors
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2427" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given two positive integers a and b, return the number of common factors of a and b. An integer x is a common factor of a and b if x divides both a and b. Example 1: Input: a = 12, b = 6 Output: 4 Explanation: The common factors of 12 and 6 are 1, 2, 3, 6. Example 2: Input: a = 25, b = 30 Output: 2 Explanation: The common factors of 25 and 30 are 1, 5. Constraints: 1 <= a, b <= 1000
Explanation
Here's the approach, followed by the Python code:
- Find the Greatest Common Divisor (GCD): The common factors of
aandbare precisely the factors of their GCD. This drastically reduces the search space. Iterate up to the Square Root of the GCD: We only need to iterate up to the square root of the GCD to find all factors. If
iis a factor ofgcd, thengcd / iis also a factor. This optimization significantly improves efficiency.Runtime Complexity: O(sqrt(min(a, b))), Storage Complexity: O(1)
Code
def commonFactors(a: int, b: int) -> int:
"""
Given two positive integers a and b, return the number of common factors of a and b.
An integer x is a common factor of a and b if x divides both a and b.
Example 1:
Input: a = 12, b = 6
Output: 4
Explanation: The common factors of 12 and 6 are 1, 2, 3, 6.
Example 2:
Input: a = 25, b = 30
Output: 2
Explanation: The common factors of 25 and 30 are 1, 5.
Constraints:
1 <= a, b <= 1000
"""
def gcd(a, b):
while(b):
a, b = b, a % b
return a
g = gcd(a, b)
count = 0
for i in range(1, int(g**0.5) + 1):
if g % i == 0:
if i * i == g:
count += 1
else:
count += 2
return count