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)
1#include <stdio.h>
2#define MOD 1000000007
3
4long gcd(long a, long b) {
5 if (b == 0) return a;
6 return gcd(b, a % b);
7}
8
9long lcm(long a, long b) {
10 return (a / gcd(a, b)) * b;
11}
12
13int nthMagicalNumber(int n, int a, int b) {
14 long left = 2, right = (long)n * a;
15 long lcm_ab = lcm(a, b);
16 while (left < right) {
17 long mid = left + (right - left) / 2;
18 if ((mid / a + mid / b - mid / lcm_ab) < n)
19 left = mid + 1;
20 else
21 right = mid;
22 }
23 return (int)(left % MOD);
24}
25
26int main() {
27 int n = 4, a = 2, b = 3;
28 printf("%d\n", nthMagicalNumber(n, a, b));
29 return 0;
30}
31
This solution defines functions to compute the Greatest Common Divisor (GCD) and the Least Common Multiple (LCM) which are used in the binary search. The search is done by iteratively halving the problem space until the nth magical number is found, which is tracked by counting the numbers <= mid divisible by either 'a' or 'b'.
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.