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)
1function nthMagicalNumber(n, a, b) {
2 const MOD = 1000000007;
3
4 function gcd(x, y) {
5 return y === 0 ? x : gcd(y, x % y);
6 }
7
8 function lcm(x, y) {
9 return (x * y) / gcd(x, y);
10 }
11
12 let lcm_ab = lcm(a, b);
13 let low = 2, high = n * Math.min(a, b);
14
15 while (low < high) {
16 let mid = Math.floor((low + high) / 2);
17 if (Math.floor(mid / a) + Math.floor(mid / b) - Math.floor(mid / lcm_ab) < n) {
18 low = mid + 1;
19 } else {
20 high = mid;
21 }
22 }
23
24 return low % MOD;
25}
26
27console.log(nthMagicalNumber(4, 2, 3));
28
The JavaScript function adopts a functional approach to calculate the nth magical number using helper functions for GCD and LCM. Binary search is performed to pinpoint the nth magical number by comparing the count against 'n', maintaining strong accuracy due to rigorous mathematical grounding.
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.