Sponsored
Sponsored
This approach leverages binary search to efficiently find the nth magical number by examining the number of magical numbers <= mid value repeatedly until we find the nth one. Calculating the Least Common Multiple (LCM) of 'a' and 'b' helps in determining magical numbers.
Time Complexity: O(log(N * min(a, b)))
Space Complexity: O(1)
1class Solution {
2 public int nthMagicalNumber(int n, int a, int b) {
3 long MOD = 1000000007;
4 long left = 2, right = (long)n * Math.min(a, b);
5 long lcm_ab = lcm(a, b);
6 while (left < right) {
7 long mid = left + (right - left) / 2;
8 if (countMagicalNumbers(a, b, lcm_ab, mid) < n) {
9 left = mid + 1;
10 } else {
11 right = mid;
12 }
13 }
14 return (int)(left % MOD);
15 }
16
17 private long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); }
18
19 private long lcm(long a, long b) { return a / gcd(a, b) * b; }
20
21 private long countMagicalNumbers(long a, long b, long lcm, long x) {
22 return x / a + x / b - x / lcm;
23 }
24}
25
The Java solution provides an elegant method to encapsulate the calculation of magical numbers through classes. This method emphasizes clean data handling by using helper functions to compute GCD and LCM, which are essential in refining the range within which we search for the nth magical number.
This approach involves generating magical numbers using a min-heap to simulate the generation process by pushing candidates generated by multiplying a set of base magical numbers with 'a' and 'b'. The minimum is repeatedly extracted until the nth magical number is found.
Time Complexity: O(n log n)
Space Complexity: O(n)
1import heapq
2
3def nthMagicalNumber(n, a, b):
4
The Python implementation uses a min-heap to manage and produce candidates for the magical numbers by systematically adding increments of 'a' and 'b'. The heap automatically keeps this collection sorted with respect to numerical magnitude, achieving efficient extraction. It ensures that duplicates (i.e., the same number coming from both sequences) are managed via conditions if a number is divisible by the increment.