Sunday 16 December 2012

gcd by subtraction - the logic

I previously described how it is possible to find the greatest common divisor of two natural numbers by using Euclid's subtraction algorithm. The logic for that algorithm is as follows:-

Label 0
Input A
Input B
If A = B then
   Goto Label 2
EndIf
If B>A then
   Store A in X
   Store B in A
   Store X in B
EndIf
Label 1
Store A-B in C
Store B in X
If X>C then
   Store B in A
   Store C in B
Else
   Store C in A
EndIf
If A is not equal to B then
   Goto Label 1
EndIf
Label 2
Display A
Goto Label 0

This processing carries out the following. The two numbers whose gcd is sought are input as A and B. If A equals B then the gcd(A,B) is simply A (or B) and there is no more work to be done. If B is greater than A, then we swap the values of A and B. Euclid's subtraction algorithm then begins after Label 1. We calculate A-B. If B is greater than A-B then we store B in A and A-B in B otherwise B remains unchanged and we store A-B in A. We repeat the process until A equals B and then we display A and stop the processing. After A is displayed, we then have the otption of returning to the beginning to process another pair of numbers.

No comments:

Post a Comment