Skip to main content
LeetCode 878, Hard. Topics: Math, Binary Search, Number Theory. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:

Problem

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 10^9 + 7.

Examples

Constraints

  • 1 <= n <= 10^9
  • 2 <= a, b <= 4 * 10^4
Follow up: Could you solve the problem in O(log(n * min(a, b))) time complexity?

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026