Math Fundamentals18 sections · 814 units
Open in Course

Nth Magical Number - Pseudocode

Implementation

function nthMagicalNumber(n, a, b):

L = lcm(a, b)

left, right = 1, n × min(a, b)

while left < right:

    mid = (left + right) // 2

    count = mid//a + mid//b - mid//L

    if count < n: left = mid + 1

    else: right = mid

return left % (10^9 + 7)

Binary search takes O(log(n × min(a, b))) time. Computing LCM is O(log min(a, b)).