Number of Common Factors — LeetCode 2427 Python Solution

EasyMathEnumerationNumber Theory
Problem
#2427
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(\min(a, b))
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview