hard Nth Magical Number
Problem Statement
Given the three integers n, a, and b, return the nth magical number modulo
A positive integer is called magical if it is divisible by either a or b.
Examples
-
Example 1:
- Input:
n = 3, a = 2, b = 3 - Expected Output: 4
- Justification: The first three magical numbers divisible by 2 or 3 are 2, 3, and 4. The third magical number is 4.
- Input:
-
Example 2:
- Input:
n = 5, a = 3, b = 4 - Expected Output: 9
- Justification: The sequence of magical numbers that are divisible by 3 or 4 begins as 3, 4, 6, 8, 9. The fifth one in this sequence is 9.
- Input:
-
Example 3:
- Input:
n = 20, a = 3, b = 5 - Expected Output: 42
- Justification: The 20th magical number for
a = 30, andb = 5is 42.
- Input:
Try it yourself
Try solving this question here:
✅ Solution Nth Magical Number
Problem Statement
Given the three integers n, a, and b, return the nth magical number modulo
A positive integer is called magical if it is divisible by either a or b.
Examples
-
Example 1:
- Input:
n = 3, a = 2, b = 3 - Expected Output: 4
- Justification: The first three magical numbers divisible by 2 or 3 are 2, 3, and 4. The third magical number is 4.
- Input:
-
Example 2:
- Input:
n = 5, a = 3, b = 4 - Expected Output: 9
- Justification: The sequence of magical numbers that are divisible by 3 or 4 begins as 3, 4, 6, 8, 9. The fifth one in this sequence is 9.
- Input:
-
Example 3:
- Input:
n = 20, a = 3, b = 5 - Expected Output: 42
- Justification: The 20th magical number for
a = 30, andb = 5is 42.
- Input:
Solution
To solve this problem, we leverage the concept of binary search along with some mathematical principles to efficiently find the nth "magical number." A magical number, in this context, is defined as any positive integer that is divisible by either of two given numbers, A or B. The key to solving this problem lies in understanding how these numbers distribute over a range and utilizing the least common multiple (LCM) of A and B to avoid redundancy. The solution involves a binary search strategy, focusing on narrowing down the range within which the nth magical number lies by counting the number of magical numbers up to a certain point and adjusting the search bounds accordingly. This method significantly reduces the number of checks needed compared to a linear search, especially for large values of N, A, and B.
The algorithm's effectiveness is rooted in its use of mathematical properties to simplify the problem. By calculating the LCM of A and B, we can accurately determine the intervals at which magical numbers occur and leverage this to estimate the position of the nth magical number within a bounded search space. Combining this with the efficiency of binary search, we can quickly converge on the exact value of the nth magical number. This approach minimizes computational overhead and ensures that the solution can handle large input values without performance degradation, making it an optimal strategy for solving the given problem.
Step-by-Step Algorithm
- Calculate the Least Common Multiple (LCM) of A and B using the Greatest Common Divisor (GCD) method. This is crucial for accurately identifying the distribution of magical numbers.
- Initialize the search bounds: Set the lower bound (
lo) to 0 and the upper bound (hi) toN * min(A, B). This range guarantees that the nth magical number lies within. - Perform binary search: Repeat the following steps until
lois less thanhi:- Calculate the mid-point (
mi) aslo + (hi - lo) / 2. - Count the total number of magical numbers less than or equal to
miby adding the numbers divisible by A, those divisible by B, and subtracting those divisible by both (to avoid double counting). - If the count is less than N, adjust
lotomi + 1to search the upper half. Otherwise, adjusthitomito search the lower half.
- Calculate the mid-point (
- Return the result: Once the loop concludes,
lowill be the nth magical number. Returnlo % MODto ensure the result is within the integer limit.
Algorithm Walkthrough
Let's consider the Input: n = 20, a = 3, b = 5
-
Calculate LCM and Initialize:
- The LCM of 3 and 5 is found using the gcd function: LCM(3, 5) = 15.
- Set
MOD = 1_000_000_007. - Initialize search bounds:
lo = 0,hi = 60(sincen * min(a, b) = 20 * 3 = 60).
-
Binary Search Iterations:
- Iteration 1:
- Mid =
(0 + 60) / 2 = 30. - Count =
30 / 3 + 30 / 5 - 30 / 15 = 10 + 6 - 2 = 14. Since 14 < 20,lobecomes31.
- Mid =
- Iteration 2:
- New bounds are
lo = 31,hi = 60. - Mid =
(31 + 60) / 2 = 45.5(using integer division, Mid = 45). - Count =
45 / 3 + 45 / 5 - 45 / 15 = 15 + 9 - 3 = 21. Since 21 >= 20,hibecomes45.
- New bounds are
- Iteration 3:
- New bounds are
lo = 31,hi = 45. - Mid =
(31 + 45) / 2 = 38. - Count =
38 / 3 + 38 / 5 - 38 / 15 = 12 + 7 - 2 = 17. Since 17 < 20,lobecomes39.
- New bounds are
- Iteration 4:
- New bounds are
lo = 39,hi = 45. - Mid =
(39 + 45) / 2 = 42. - Count =
42 / 3 + 42 / 5 - 42 / 15 = 14 + 8 - 2 = 20. Since 20 == 20, and we're looking for the least value oflothat meets this condition,hibecomes42.
- New bounds are
- Iteration 5:
- New bounds are
lo = 39,hi = 42. - Mid =
(39 + 42) / 2 = 40.5(using integer division, Mid = 40). - Count =
40 / 3 + 40 / 5 - 40 / 15 = 13 + 8 - 2 = 19. Since 19 < 20,lobecomes41.
- New bounds are
- Iteration 6:
- New bounds are
lo = 41,hi = 42. - Mid =
(41 + 42) / 2 = 41.5(using integer division, Mid = 41). - Count =
41 / 3 + 41 / 5 - 41 / 15 = 13 + 8 - 2 = 19(same as last time, since Mid didn't change effectively). Since 19 < 20,lobecomes42.
- New bounds are
- Iteration 7:
- Now
lo = 42andhi = 42, so the loop terminates.
- Now
- Iteration 1:
-
Final Result:
- The loop has exited with
lo = 42, which is the value we consider to be the 20th magical number givena = 3andb = 5.
- The loop has exited with
-
Modulus Operation:
- Apply the modulus operation:
42 % MOD = 42.
- Apply the modulus operation:
Code
public class Solution {
// Method to find the nth magical number
public int nthMagicalNumber(int N, int A, int B) {
int MOD = 1_000_000_007; // Define the modulus value to ensure the result fits within the integer limits
int L = (A / gcd(A, B)) * B; // Calculate the least common multiple (LCM) of A and B using the gcd
long lo = 0; // Set the lower bound of our search
long hi = (long) N * Math.min(A, B); // Set the upper bound of our search based on the minimum of A and B
// Use binary search to find the nth magical number
while (lo < hi) {
long mi = lo + (hi - lo) / 2; // Calculate the middle point of our current search space
// If there are not enough magical numbers below or equal to mi...
if (mi / A + mi / B - mi / L < N) lo = mi + 1; // ...then we need to search the higher half
else hi = mi; // ...else search the lower half
}
return (int) (lo % MOD); // Return the nth magical number modulo MOD
}
// Helper method to compute the greatest common divisor (gcd) of x and y
public int gcd(int x, int y) {
if (x == 0) return y; // Base case: if x is 0, gcd is y
return gcd(y % x, x); // Recursive call: gcd of y % x and x
}
// Main method to test the nthMagicalNumber method with example inputs
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1: Input: N = 3, A = 2, B = 3
System.out.println(solution.nthMagicalNumber(3, 2, 3));
// Expected Output: 2
// Example 2: Input: N = 5, A = 3, B = 4
System.out.println(solution.nthMagicalNumber(5, 3, 4));
// Expected Output: 9
// Example 3: Input: N = 20, A = 30, B = 5
System.out.println(solution.nthMagicalNumber(20, 3, 5));
// Expected Output: 42
}
}
Complexity Analysis
Time Complexity
: The main operation in this code is the binary search algorithm. The search space is between 0 and . The binary search algorithm has a logarithmic time complexity relative to the size of the search space. Therefore, the time complexity is , as each iteration of the loop halves the search space until the solution is found.
Space Complexity
: The algorithm uses a constant amount of space regardless of the input size. Thus, the space complexity of the algorithm is , indicating that it uses a fixed amount of memory.
🤖 Don't fully get this? Learn it with Claude
Stuck on Nth Magical Number? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Nth Magical Number** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Nth Magical Number** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Nth Magical Number**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Nth Magical Number**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.