3

I have two natural numbers, $x$ and $y$. I repeatedly subtract the smaller one from the bigger one until $x$ and $y$ are both 1.

I need to find how many times I have do that for a given $x$ and $y$, if it is possible. If it's not possible to get to x=1 and y=1, I want to know that.

Example:
x=7, y=4
x=3, y=4
x=3, y=1
x=2, y=1
x=1,y=1
Done. Took 4 steps.

Example 2:
x=4, y=2
x=2, y=2
-> Impossible

I could just repeat the steps over and over, but I need to find the answer for potentially really big numbers, and I suspect a rather easy pattern. The steps seem to be related to the difference between x and y, but the pattern only worked for values up until 9.

None of the patterns I found worked for all the numbers, so some help would be appreciated.

Blue
  • 75,673
Finn
  • 159

1 Answers1

7

The pattern here is: you can reach $1$ if and only if the original numbers $x$ and $y$ are coprime, i.e. their GCD ("greatest common divisor") is $1$. The other way of saying that is that $x$ and $y$ have no common prime factors.

As for how to determine it for really big $x$ and $y$ - you speed up the process by skipping steps: if e.g. $x>y$, then you can immediately skip from $(x,y)$ to $(r,y)$ where $r$ is the remainder in the (say, long) division of $x$ by $y$. What you get then is so-called Euclidean algorithm for calculation of GCD (Wikipedia) and is pretty efficient. I guess your best bet is just to apply the algorithm and see whether you end up with $1$ and how many steps it took.