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
    
        

猜你喜欢

转载自blog.csdn.net/zjucor/article/details/81269445