Ugly Number III
Advertisement
Problem
Find the nth positive integer that is divisible by a, b, or c.
Key insight: Binary search on the answer. Count multiples of a, b, c up to x using inclusion-exclusion: |A∪B∪C| = |A|+|B|+|C| - |A∩B| - |A∩C| - |B∩C| + |A∩B∩C|.
Solutions
# Python
from math import gcd
def nthUglyNumber(n, a, b, c):
def lcm(x, y): return x * y // gcd(x, y)
ab = lcm(a, b); ac = lcm(a, c); bc = lcm(b, c); abc = lcm(ab, c)
def count(x):
return x//a + x//b + x//c - x//ab - x//ac - x//bc + x//abc
lo, hi = 1, 2 * 10**9
while lo < hi:
mid = (lo + hi) // 2
if count(mid) >= n:
hi = mid
else:
lo = mid + 1
return lo
// C++
long long gcd(long long a, long long b){ return b?gcd(b,a%b):a; }
long long lcm(long long a, long long b){ return a/gcd(a,b)*b; }
int nthUglyNumber(int n, int a, int b, int c) {
long long ab=lcm(a,b),ac=lcm(a,c),bc=lcm(b,c),abc=lcm(ab,c);
auto count=[&](long long x){ return x/a+x/b+x/c-x/ab-x/ac-x/bc+x/abc; };
long long lo=1,hi=2e9;
while(lo<hi){long long mid=(lo+hi)/2;if(count(mid)>=n)hi=mid;else lo=mid+1;}
return lo;
}
// Java
long gcd(long a, long b){ return b==0?a:gcd(b,a%b); }
long lcm(long a, long b){ return a/gcd(a,b)*b; }
public int nthUglyNumber(int n, int a, int b, int c) {
long ab=lcm(a,b),ac=lcm(a,c),bc=lcm(b,c),abc=lcm(ab,c);
long lo=1,hi=2000000000L;
while(lo<hi){
long mid=(lo+hi)/2;
long cnt=mid/a+mid/b+mid/c-mid/ab-mid/ac-mid/bc+mid/abc;
if(cnt>=n)hi=mid;else lo=mid+1;
}
return (int)lo;
}
// JavaScript
function nthUglyNumber(n, a, b, c) {
const gcd = (x, y) => y ? gcd(y, x%y) : x;
const lcm = (x, y) => x / gcd(x, y) * y;
const ab=lcm(a,b),ac=lcm(a,c),bc=lcm(b,c),abc=lcm(ab,c);
const count = x => Math.floor(x/a)+Math.floor(x/b)+Math.floor(x/c)-Math.floor(x/ab)-Math.floor(x/ac)-Math.floor(x/bc)+Math.floor(x/abc);
let lo=1n,hi=2000000000n;
// Use number version
let lo2=1,hi2=2e9;
while(lo2<hi2){const mid=Math.floor((lo2+hi2)/2);if(count(mid)>=n)hi2=mid;else lo2=mid+1;}
return lo2;
}
Complexity
- Time: O(log(2×10^9))
- Space: O(1)
Advertisement
← Previous
Maximum Performance of a TeamNext →
Design Twitter