Ctrl K

Distinct GCDs of Selections

Hard
You are given an array of positive integers values. Pick any non-empty selection of its elements (elements are taken by position, order does not matter) and compute the greatest common divisor (GCD) of the chosen numbers. The GCD of a single number is the number itself. How many distinct GCD values can you get across all non-empty selections? There are exponentially many selections, so enumerating them is not the way.
Example 1
values=[12, 18, 8] → 6

Single elements give 12, 18 and 8; pairs give gcd(12, 18) = 6, gcd(12, 8) = 4, gcd(18, 8) = 2; all three give 2. That makes six distinct values: 12, 18, 8, 6, 4, 2.

Example 2
values=[7, 7, 14] → 2

Any selection containing a 7 gives 7, and 14 alone gives 14. Two values in total.

Example 3
values=[9] → 1
Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 2 · 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPair GCDs by Sorted Position HardEven Piles of Cards EasyPhoto Frames of the Same Shape MediumCoprime Digit Pairs EasyPrimes Along Grid Rays Medium
loading Python…
Input
values=[12, 18, 8]
Expected
6

Run checks the first 3 tests in your browser. Submit checks all 101 tests on the server, hidden ones included.