Practice › Binary Search
Nth Magical Number
Hard · Binary Search · Asked at Google, Amazon
A positive integer is magical if it is divisible by a or by b. Print the n-th magical number modulo 10^9 + 7.
Input
A single line with n, a and b.
Output
The n-th magical number modulo 10^9 + 7.
Constraints
- 1 ≤ n ≤ 10^9
- 2 ≤ a, b ≤ 4 × 10^4
The count of magical numbers ≤ x is x/a + x/b − x/lcm(a, b) (inclusion–exclusion). It only grows with x, so binary search the smallest x whose count is ≥ n. x can reach 4 × 10^13 — use 64-bit integers, and take the modulo only at the end.
Example 1
Input
1 2 3
Output
2
Example 2
Input
4 2 3
Output
6
Example 3
Input
5 2 4
Output
10
Hints
- Counting magical numbers up to x is easy with inclusion–exclusion.
- The count only grows as x grows — binary search on x.
- The answer is at most n · min(a, b).
Approach
count(x) = ⌊x/a⌋ + ⌊x/b⌋ − ⌊x/lcm(a, b)⌋, with lcm = a / gcd(a, b) × b. Binary search the smallest x in [1, n · min(a, b)] with count(x) ≥ n — that x is itself magical. All of this needs 64-bit integers (x can reach 4 × 10^13); take the result modulo 10^9 + 7 only when printing.
Complexity: O(log(n · min(a, b))) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, a, b;
cin >> n >> a >> b;
long long l = a / __gcd(a, b) * b;
long long lo = 1, hi = n * min(a, b);
while (lo < hi) {
long long m = lo + (hi - lo) / 2;
if (m / a + m / b - m / l >= n) hi = m;
else lo = m + 1;
}
cout << lo % 1000000007LL << "\n";
return 0;
}Python solution
from math import gcd
n, a, b = map(int, input().split())
l = a // gcd(a, b) * b
lo, hi = 1, n * min(a, b)
while lo < hi:
m = (lo + hi) // 2
if m // a + m // b - m // l >= n:
hi = m
else:
lo = m + 1
print(lo % (10**9 + 7))Java solution
import java.util.*;
public class Main {
static long gcd(long x, long y) { return y == 0 ? x : gcd(y, x % y); }
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong(), a = sc.nextLong(), b = sc.nextLong();
long l = a / gcd(a, b) * b;
long lo = 1, hi = n * Math.min(a, b);
while (lo < hi) {
long m = lo + (hi - lo) / 2;
if (m / a + m / b - m / l >= n) hi = m;
else lo = m + 1;
}
System.out.println(lo % 1000000007L);
}
}