[Swift]LeetCode878. 第 N 個神奇數字 | Nth Magical Number

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-uppysjfr-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

A positive integer is magical if it is divisible by either A or B.git

Return the N-th magical number.  Since the answer may be very large, return it modulo 10^9 + 7github

Example 1:微信

Input: N = 1, A = 2, B = 3 Output: 2 

Example 2:spa

Input: N = 4, A = 2, B = 3 Output: 6 

Example 3:code

Input: N = 5, A = 2, B = 4 Output: 10 

Example 4:htm

Input: N = 3, A = 6, B = 4 Output: 8 

Note:blog

  1. 1 <= N <= 10^9
  2. 2 <= A <= 40000
  3. 2 <= B <= 40000

若是正整數能夠被 A 或 B 整除,那麼它是神奇的。get

返回第 N 個神奇數字。因爲答案可能很是大,返回它模 10^9 + 7 的結果。 input

示例 1:

輸入:N = 1, A = 2, B = 3
輸出:2

示例 2:

輸入:N = 4, A = 2, B = 3
輸出:6

示例 3:

輸入:N = 5, A = 2, B = 4
輸出:10

示例 4:

輸入:N = 3, A = 6, B = 4
輸出:8 

提示:

  1. 1 <= N <= 10^9
  2. 2 <= A <= 40000
  3. 2 <= B <= 40000

Runtime: 4 ms
Memory Usage: 18.4 MB
 1 class Solution {
 2     func nthMagicalNumber(_ N: Int, _ A: Int, _ B: Int) -> Int {
 3         var a:Int = A
 4         var b:Int = B
 5         var tmp:Int = 0
 6         var l:Int = 2
 7         var r:Int = Int(1e14)
 8         var mod:Int = Int(1e9 + 7)
 9         while (b > 0)
10          {
11             tmp = a
12             a = b
13             b = tmp % b
14         }
15         while (l < r)
16         {
17             var m:Int = (l + r) / 2;
18             if m / A + m / B - m / (A * B / a) < N
19             {
20                 l = m + 1
21             }
22             else
23             {
24                 r = m
25             }
26         }
27         return Int(l % mod)
28     }
29 }
相關文章
相關標籤/搜索