Understanding recursive function for finding GCF of 2 numbers

2.4k Views Asked by At

So I get how this code works, but I don't understand why it works. The function assumes input num1 > num2. Algorithms are hard for me to grasp, so please explain to me like I'm five.
Heres the javascript code:

function recursiveDivision(num1, num2) {
    if (num2 === 0) {
      return num1
    } else {
      return recursiveDivision(num2, num1%num2);
    }
  }
1

There are 1 best solutions below

0
On

Let $d = \gcd (m, n)$ with $m > n$. By the Euclidean division theorem, you can write $m = qn + r$, with $r < n$. Now, since $d | m$ and $d | n$ then $d | r = m - qn$, so $d$ is a common divisor of $n$ and $r$, but not necessarily the greatest one. Asume that there is $D \ge d$ dividing $n$ and $r$. Then it would have to also divide $m = qn+r$, and then it would divide $\gcd (m n) = d$. So, $D | d$ and since it was assumed that $D \ge d$, then $D=d$. Therefore, $\gcd (m ,n) = \gcd (n, r)$ (in your notation, r = m % n).