Proving termination for gcd subtract algorithm

421 Views Asked by At

Im trying to show that the following algorithm terminates when a,b are larger than zero. I tried it firstly by complete induction for (a,n) when n is any number but got stuck at the case that n > a. Is there other way to show it? thanks

while (a!=b) {
        if (a>b) 
            a=a-b;
        else
            b=b-a;
     }
1

There are 1 best solutions below

0
On BEST ANSWER

Each iteration changes only one variable $a$ or $b$. If $a$ is changed, $a_{new}> 0$ is obvious. If $b$ is changed, $b_{new} \ge 0$ is obvious, but it follows $b_{new} > 0$ because equality happens only when $a=b$ and in this case the loop would have stopped.

This means after each loop iteration the values of $a$ and $b$ are again both positive. But the value of their sum has decreased, it was $a_{old}+b_{old}$ before but is now $a_{old}$ (if $a$ changed) or $b_{old}$ (if $b$ changed). So after each loop iteration, we get a smaller (but still positive) value as the sum $a+b$. This means the loop must stop.