878. Nth Magical Number
Posted ruruozhenhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了878. Nth Magical Number相关的知识,希望对你有一定的参考价值。
A positive integer is magical if it is divisible by either A or B.
Return the N-th magical number. Since the answer may be very large, return it modulo 10^9 + 7
.
Example 1:
Input: N = 1, A = 2, B = 3
Output: 2
Example 2:
Input: N = 4, A = 2, B = 3
Output: 6
Example 3:
Input: N = 5, A = 2, B = 4
Output: 10
Example 4:
Input: N = 3, A = 6, B = 4
Output: 8
Note:
1 <= N <= 10^9
2 <= A <= 40000
2 <= B <= 40000
Approach #1: Binary Serach + Brute Froce. [Time limit exceeded]
class Solution { public: int nthMagicalNumber(int N, int A, int B) { long l = 1, r = N * min(A, B); while (l <= r) { long m = l + (r - l) / 2; int num = 0; for (int i = 1; i <= m; ++i) { if (i % A == 0 || i % B == 0) num++; } if (num >= N) r = m - 1; else l = m + 1; } return l; } };
Approach #2: Binary Serach + LCM.
class Solution { public: int nthMagicalNumber(int N, int A, int B) { int MOD = 1e9 + 7; int L = A / gcd(A, B) * B; long l = 0, r = (long) 1e15; while (l < r) { long m = l + (r - l) / 2; long num = m / A + m / B - m / L; // not int type if (num < N) l = m + 1; else r = m; } return (int) (l % MOD); } private: int gcd(int x, int y) { if (x == 0) return y; return gcd(y % x, x); } };
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Nth Magical Number.
以上是关于878. Nth Magical Number的主要内容,如果未能解决你的问题,请参考以下文章
[Daily Coding Problem 70] Nth perfect number