Problem 374634 · medium · Phase 03 Linear Management & Searching

Nth Number Divisible by Either

binary search on the answer · inclusion-exclusion · math

Given positive integers n, a and b, return the n-th smallest positive integer that is divisible by a or b.

Examples

Input:  n = 3, a = 2, b = 3
Output: 4
Explanation: the sequence starts 2, 3, 4, 6, 8, 9, ...

Input:  n = 5, a = 4, b = 6
Output: 16
Explanation: 4, 6, 8, 12, 16, ...

Input:  n = 1, a = 7, b = 7
Output: 7

Constraints

  • 1 <= n <= 10**9, 1 <= a, b <= 4 * 10**4
  • Required time: O(log(n * min(a, b))). Generating the sequence term by term is far too slow.

Goals

  • Count multiples of a or b up to x with inclusion-exclusion
  • Search a huge value range with a cheap O(1) counting function
Starting Python…