-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution878.cs
48 lines (41 loc) · 1012 Bytes
/
Solution878.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution878
{
/// <summary>
/// 878. Nth Magical Number - Hard
/// <a href="https://leetcode.com/problems/nth-magical-number">See the problem</a>
/// </summary>
public int NthMagicalNumber(int n, int a, int b)
{
int mod = 1_000_000_007;
long lcm = (long)a * b / Gcd(a, b);
long left = 2;
long right = (long)1e14;
while (left < right)
{
long mid = left + (right - left) / 2;
long count = mid / a + mid / b - mid / lcm;
if (count < n)
{
left = mid + 1;
}
else
{
right = mid;
}
}
return (int)(left % mod);
}
private long Gcd(long a, long b)
{
while (b != 0)
{
long temp = b;
b = a % b;
a = temp;
}
return a;
}
}