Locate the Nth Positive Multiple of Either of Two Divisors

Quick Overview

Locate the Nth Positive Multiple of Either of Two Divisors. A positive number qualifies if it is divisible by a or by b, counting numbers divisible by both only once.

Locate the Nth Positive Multiple of Either of Two Divisors

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

### Problem A positive number qualifies if it is divisible by a or by b, counting numbers divisible by both only once. Return the nth qualifying number modulo `10^9+7`. ```cpp class Solution { public: int nthMagicalNumber(int n, int a, int b); }; ``` ### Examples **Example 1:** ```text Input: n = 5, a = 3, b = 4 Output: 9 Explanation: The qualifying sequence begins3,4,6,8,9. ``` **Example 2:** ```text Input: n = 4, a = 4, b = 4 Output: 16 Explanation: Equal divisors contribute one sequence,4,8,12,16. ``` ### Constraints - `1 <= n <= 10^9`. - `2 <= a,b <= 4*10^4`. ### Contract considerations The ordering is over unreduced positive integers; only the returned value is reduced. ```hint Read the boundary condition Count qualifying values below a candidate rather than generating the sequence. ``` ### Boundary reminders The ordering is over unreduced positive integers; only the returned value is reduced.

Overview: Locate the Nth Positive Multiple of Either of Two Divisors. A positive number qualifies if it is divisible by a or by b, counting numbers divisible by both only once.

Google logo
Google
Jun 25, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

Problem

A positive number qualifies if it is divisible by a or by b, counting numbers divisible by both only once. Return the nth qualifying number modulo 10^9+7.

class Solution {
public:
    int nthMagicalNumber(int n, int a, int b);
};

Examples

Example 1:

Input: n = 5, a = 3, b = 4
Output: 9
Explanation: The qualifying sequence begins3,4,6,8,9.

Example 2:

Input: n = 4, a = 4, b = 4
Output: 16
Explanation: Equal divisors contribute one sequence,4,8,12,16.

Constraints

  • 1 <= n <= 10^9 .
  • 2 <= a,b <= 4*10^4 .

Contract considerations

The ordering is over unreduced positive integers; only the returned value is reduced.

Boundary reminders

The ordering is over unreduced positive integers; only the returned value is reduced.