The tree is as follows:
(1,1) / \ (2,1) (1,2) / \ / \ (3,1)(2,3) (3,2)(1,3) and onward
The root is (1,1), all values in the tree are tuples.
Where (x,y) is an element of the tree: The leftChild will be (x+y,y) The rightChild will be (x,x+y)
I am building a function that finds the distance from the root (1,1). I cannot build the tree from scratch as it will be too time consuming.
I have found that 1 distance from the tuple being searched for we must subtract the the max with the min. We can work backward.
1 2 (3,2)->(1,2)->(1,1) (3,2)->(3-2,2) = (1,2)->(1,2-1) = (1,1) given this is always true: if x > y: newtuple = (x-y,y) distance += 1 else if y > x: newtuple = (x,y-x) distance += 1
Yet because possible test cases can go up to even x = 10^50, this is even too slow.
So I have found a formally to find the amount of subtractions of x with y or vice versa to make a x > y change to y < x and vice versa until (x,y) = (1,1).
So X - Y(a certain amount of times, say z) will make x less than y... X - Y*z = y find z via algebra... z = (Y-X)/(-Y)
This is my code so far:
from decimal import Decimal import math def answer(M,F): M = int(M) F = int(F) i = 0 while True: if M == 1 and F == 1: return str(i) if M > F: x = math.ceil((F-M)/(-F)) M -= F*x elif F > M: x = math.ceil((M-F)/(-M)) F -= M*x else: if F == M and F != 1: return "impossible" i += x if M < 1 or F < 1: return "impossible" return str(i)
And it's not passing some unknown test cases, yet passes all the test cases I can think of. What test cases could I be failing? Where is my code wrong?
p.s. used Decimal module, just removed from code to make more readible.