LeetCode 0878. Nth Magical Number Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
0878. Nth Magical Number

Description

A positive integer is magical if it is divisible by either a or b.

Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.

 

Example 1:

Input: n = 1, a = 2, b = 3
Output: 2

Example 2:

Input: n = 4, a = 2, b = 3
Output: 6

 

Constraints:

  • 1 <= n <= 109
  • 2 <= a, b <= 4 * 104

Solutions

Solution 1

PythonJavaC++Go
class Solution: def nthMagicalNumber(self, n: int, a: int, b: int) -> int: mod = 10**9 + 7 c = lcm(a, b) r = (a + b) * n return bisect_left(range(r), x=n, key=lambda x: x // a + x // b - x // c) % mod(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !