Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

878. Nth Magical Number

Hard35.8% Acceptance
MathBinary Search
Asked by:
G
Google
ProblemSolutions (7)VideosCompanies (1)Notes

Problem Statement

A positive integer is magical if it is divisible by either a or b.

Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.

Example 1:

Input: n = 1, a = 2, b = 3
Output: 2

Example 2:

Input: n = 4, a = 2, b = 3
Output: 6

Constraints:

  • 1 <= n <= 109
  • 2 <= a, b <= 4 * 104
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions

Approach

The key idea in #878 Nth Magical Number is to find the n-th number divisible by either of two integers. A direct simulation would be inefficient for large values, so the optimal approach relies on binary search combined with mathematical counting.

Instead of generating numbers, we search for the smallest value x such that there are at least n numbers less than or equal to x that are divisible by either of the given integers. Using the Least Common Multiple (LCM), we can avoid double-counting values divisible by both numbers. For any candidate value, we count how many valid numbers exist using a mathematical formula and adjust the binary search range accordingly.

This transforms the problem from enumeration to searching the answer space. The method is efficient even for very large constraints because each step halves the search range while using constant-time arithmetic operations.

Complexity

ApproachTime ComplexitySpace Complexity
Binary Search with LCM-based CountingO(log(N × min(a, b)))O(1)

Video Solution Available

GeeksforGeeks

View all video solutions

Solutions (7)

Binary Search Approach

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)

CC++JavaPythonC#JavaScript
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

Explanation

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'.

Min-Heap Based Approach

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



Video Solutions

Watch expert explanations and walkthroughs

Find nth Magic Number | GeeksforGeeks

GeeksforGeeks
4:2319,844 views

Asked By Companies

1 companies
G
Google

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Sqrt(x)Easy
Missing NumberEasy
Valid Perfect SquareEasy
Nth DigitMedium
More similar problems

Related Topics

MathBinary Search

Problem Stats

Acceptance Rate35.8%
DifficultyHard
Companies1

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Is Nth Magical Number asked in FAANG interviews?

Yes, variations of this problem appear in interviews at large tech companies. It tests understanding of binary search on answer space, number theory concepts like LCM, and efficient counting strategies.

What data structure is used in Nth Magical Number?

This problem does not rely on complex data structures. It primarily uses mathematical operations and binary search, along with computing the greatest common divisor (GCD) to derive the LCM.

What is the optimal approach for Nth Magical Number?

The optimal approach uses binary search on the answer space combined with mathematical counting. By calculating how many numbers up to a candidate value are divisible by the given integers using LCM, we can efficiently determine whether we have reached the nth magical number.

Why is LCM important in the Nth Magical Number problem?

LCM helps avoid double-counting numbers that are divisible by both given integers. When counting valid numbers up to a value, subtracting those divisible by the LCM ensures accurate inclusion-exclusion counting.

MOD
=
10
**
9
+
7
5
lcm_ab
=
a
*
b
//
gcd
(
a
,
b
)
6
heap
=
[
]
7
heapq
.
heappush
(
heap
,
a
)
8
heapq
.
heappush
(
heap
,
b
)
9
10
magical_number
=
0
11
for
_
in
range
(
n
)
:
12
magical_number
=
heapq
.
heappop
(
heap
)
13
if
not
magical_number
%
a
:
14
heapq
.
heappush
(
heap
,
magical_number
+
a
)
15
if
not
magical_number
%
b
:
16
heapq
.
heappush
(
heap
,
magical_number
+
b
)
17
18
return
magical_number
%
MOD
19
20
from
math
import
gcd
21
22
# Example usage:
23
print
(
nthMagicalNumber
(
4
,
2
,
3
)
)
24

Explanation

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.