mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-25 03:11:41 +08:00
27 lines
478 B
Go
27 lines
478 B
Go
package leetcode
|
|
|
|
func nthMagicalNumber(N int, A int, B int) int {
|
|
low, high := int64(0), int64(1*1e14)
|
|
for low < high {
|
|
mid := low + (high-low)>>1
|
|
if calNthMagicalCount(mid, int64(A), int64(B)) < int64(N) {
|
|
low = mid + 1
|
|
} else {
|
|
high = mid
|
|
}
|
|
}
|
|
return int(low) % 1000000007
|
|
}
|
|
|
|
func calNthMagicalCount(num, a, b int64) int64 {
|
|
ab := a * b / gcd(a, b)
|
|
return num/a + num/b - num/ab
|
|
}
|
|
|
|
func gcd(a, b int64) int64 {
|
|
for b != 0 {
|
|
a, b = b, a%b
|
|
}
|
|
return a
|
|
}
|