Solution: Nth Magical Number

Let’s solve the Nth Magical Number using the Math and Geometry pattern.

Statement

Given three integers n, a, and b, return the nth magical number.

A magical number is defined as a positive integer that is divisible by either a or b.

As the result may be very large, return it modulo 109+710^9+7.

Constraints:

  • 11 \leq n 109\leq 10^9

  • 22 \leq a, b 4×104\leq 4 \times 10^4

Solution

To find the nth number divisible by either a or b, we observe that magical numbers form a sorted sequence of all multiples of a and b. Instead of generating this sequence explicitly, we can efficiently count how many magical numbers are x\leq x using the inclusion-exclusion principle:

  • Count of numbers divisible by a: x/a\lfloor x / a \rfloor

  • Count of numbers divisible by b: x/b\lfloor x / b \rfloor

  • Subtract numbers divisible by both (i.e., x/lcm(a,b)\lfloor x / lcm(a, b) \rfloor) to avoid double counting.

Where the least common multiple (LCM) of two numbers, aa and bb, is the smallest number divisible by both, and is given by:

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.