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