Ctrl K

N-th Multiple of Either Divisor

Hard
You are given two divisors, first and second. Write out, in increasing order, every positive integer divisible by at least one of them (a number divisible by both appears once). Return the number at position rank in that list (counting from one). The answer can be huge, so return it modulo 10⁹ + 7. Walking through the numbers one at a time is too slow: rank can be as large as a billion.
Example 1
rank=5, first=4, second=6 → 16

The qualifying numbers in increasing order are 4, 6, 8, 12, 16, … The fifth is 16. The number 12 divides by both but is counted once.

Example 2
rank=3, first=5, second=5 → 15

Both divisors are equal, so these are just the multiples of five: 5, 10, 15.

Example 3
rank=1000000000, first=2, second=2 → 999999993
Constraints
  • 1 ≤ rank ≤ 10⁹
  • 2 ≤ first, second ≤ 4 · 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsA Base of All Ones HardK-th Value in a Times Table HardFactorials With Exactly K Trailing Zeros HardPrototype Drop Tests HardNumbers From Working Keys Hard
loading Python…
Input
rank=5, first=4, second=6
Expected
16

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