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 <iostream>
2#include <algorithm>
3#define MOD 1000000007
4
5using namespace std;
6
7long gcd(long a, long b) {
8 return b == 0 ? a : gcd(b, a % b);
9}
10
11long lcm(long a, long b) {
12 return (a / gcd(a, b)) * b;
13}
14
15int nthMagicalNumber(int n, int a, int b) {
16 long left = 2, right = (long)n * min(a, b);
17 long lcm_ab = lcm(a, b);
18 while (left < right) {
19 long mid = left + (right - left) / 2;
20 if ((mid / a + mid / b - mid / lcm_ab) < n)
21 left = mid + 1;
22 else
23 right = mid;
24 }
25 return left % MOD;
26}
27
28int main() {
29 int n = 4, a = 2, b = 3;
30 cout << nthMagicalNumber(n, a, b) << endl;
31 return 0;
32}
33
The C++ solution closely parallels the logic implemented in C. It calculates the LCM, and uses binary search to determine the nth magical number. The division in the search counts the number of multiples of 'a' and 'b' minus the multiples of LCM, allowing the program to check if mid is a possible candidate.
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.