Solution: Nth Magical Number
Let’s solve the Nth Magical Number using the Math and Geometry pattern.
We'll cover the following
Statement
Given three integers n
, a
, and b
, return the n
th
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
Constraints:
n
a
,b
Solution
To find the n
th
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
Count of numbers divisible by
a
:Count of numbers divisible by
b
:Subtract numbers divisible by both (i.e.,
) to avoid double counting.
Where the least common multiple (LCM) of two numbers,
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.