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. 1 <= N <= 10^9
  2. 2 <= A <= 40000
  3. 2 <= B <= 40000

整除+第N个数,容易想到是二分,直接二分结果即可,

class Solution:
    def nthMagicalNumber(self, N, A, B):
        """
        :type N: int
        :type A: int
        :type B: int
        :rtype: int
        """
        def getGCD(a,b):
            a, b = (a, b) if a>=b else (b, a)
            while b:
                a,b = b, a%b
            return a
        C = A//getGCD(A,B)*B
        
        def getNN():
            lo,hi=min(A,B),N*min(A,B)
            while lo<hi:
                mid=(lo+hi)//2
                t = mid
                c0 = t//A+t//B-t//C
                if c0>N: hi=mid-1
                elif c0<N: lo=mid+1
                else: return mid
#                print(mid)
            return lo
        res = getNN()
        while not (res%A==0 or res%B==0): res-=1
        return res%1000000007
    
        

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`_.nth` 函数是 Lodash 中的一个工具函数,用于获取数组 `array` 中第 `num` 个元素。它的源码实现如下: ```javascript function nth(array, n) { var length = array == null ? 0 : array.length if (!length) { return } n += n < 0 ? length : 0 return isIndex(n, length) ? array[n] : undefined } ``` 该函数首先判断传入的数组是否为空,如果为空则直接返回 `undefined`。然后对传入的 `num` 进行一些处理,如果 `num` 是负数,则将其转化为正数。最后,通过 `isIndex` 函数判断 `num` 是否为有效的下标,如果是,则返回对应元素,否则返回 `undefined`。 其中,`isIndex` 函数的实现如下: ```javascript function isIndex(value, length) { var type = typeof value length = length == null ? MAX_SAFE_INTEGER : length return !!length && (type === 'number' || (type !== 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length) } ``` 该函数用于判断一个值是否为有效的数组下标。它首先判断传入的 `length` 是否为有效的数字,然后判断 `value` 是否为有效的数字或字符串,并且在范围内。如果满足以上条件,则返回 `true`,否则返回 `false`。 需要注意的是,`reIsUint` 是一个正则表达式,用于判断一个字符串是否表示一个非负整数: ```javascript var reIsUint = /^(?:0|[1-9]\d*)$/ ``` 综上所述,`_.nth` 函数是一个简单实用的工具函数,用于获取数组中指定位置的元素,并且具有较好的健壮性和可读性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值