DeepRest

Nth Magical Number

Dec 11th, 2021
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. class Solution(object):
  2.     def nthMagicalNumber(self, n, a, b):
  3.         """
  4.        :type n: int
  5.        :type a: int
  6.        :type b: int
  7.        :rtype: int
  8.        """
  9.         def gcd (a, b):
  10.             if a == 0:
  11.                 return b
  12.             return gcd(b%a, a)
  13.  
  14.         lcm = a*b//gcd(a,b)
  15.         cyc = lcm//a + lcm//b - 1
  16.         res = n//cyc * lcm
  17.         n = n%cyc
  18.  
  19.         if n == 0:
  20.             return res%int(1e9+7)
  21.         if n == 1:
  22.             return (res + min(a,b))%int(1e9+7)
  23.        
  24.         lo,hi = min(a,b)+1, lcm-1
  25.         mid = (lo + hi)//2
  26.         while (lo < hi):
  27.             tar = mid//a + mid//b
  28.             if n <= tar:
  29.                 hi = mid
  30.             else:
  31.                 lo = mid + 1
  32.             mid = (lo + hi)//2
  33.         return (res+lo)%int(1e9+7)
Advertisement
Add Comment
Please, Sign In to add comment