Number of Common Factors — LeetCode 2427 Python Solution
- Problem
- #2427
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- Input
- a = 12, b = 6
- Output
- 4
- Explanation
- The common factors of 12 and 6 are 1, 2, 3, 6.
Python solution
class Solution:
def commonFactors(self, a: int, b: int) -> int:
g = gcd(a, b)
return sum(g % x == 0 for x in range(1, g + 1))Complexity
| Measure | Complexity |
|---|---|
| Time | O(\min(a, b)) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2427. Number of Common Factors is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2427. Number of Common Factors?
- LeetCode 2427. Number of Common Factors is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2427. Number of Common Factors?
- The Python solution on this page runs in O(\min(a, b)).
- What is the space complexity of LeetCode 2427. Number of Common Factors?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2427. Number of Common Factors cover?
- LeetCode 2427. Number of Common Factors is tagged Math, Enumeration and Number Theory on LeetCode.