Find minimum number of iterations to reach a certain sum

前端 未结 2 1605
挽巷
挽巷 2021-01-12 11:10

I\'m trying to solve this problem since weeks, but couldn\'t arrive to a solution. You start with two numbers X and Y both equal to 1. Only valid options are X+Y

2条回答
  •  离开以前
    2021-01-12 11:15

    Now I can give an O(nlogn) solution.

    The method seems like greatest common divisor

    Use f(x, y) express the minimum number of iterations to this state. This state can be reached by f(x-y, y) if x>y or f(x,y-x) if x. We can see that the way to reach state (x, y) is unique, we can calculate it in O(logn) like gcd.

    The answer is min( f(n, i) | 1 <= i < n) so complexity is O(nlogn)

    python code:

    def gcd (n, m):
        if m == 0:
            return n
        return gcd (m, n%m)
    
    def calculate (x, y):
        if y == 0:
            return -1
        return calculate (y, x%y) + x/y
    
    def solve (n):
        x = 0
        min = n
        for i in xrange (1, n):
            if gcd (n, i) == 1:
                ans = calculate (n, i)
                if ans < min:
                    min = ans
                    x = i
        print min
    
    if __name__ == '__main__':
        solve (5)
    

提交回复
热议问题