Find minimum number of iterations to reach a certain sum

前端 未结 2 1606
挽巷
挽巷 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<y. 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)
    
    0 讨论(0)
  • 2021-01-12 11:23

    If the numbers are not that big (say, below 1000), you can use a breadth-first search.

    Consider a directed graph where each vertex is a pair of numbers (X,Y), and from each such vertex there are two edges to vertices (X+Y,Y) and (X,X+Y). Run a BFS on that graph from (0,0) until you reach any of the positions you need.

    0 讨论(0)
提交回复
热议问题