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
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)
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.