Sometimes computers need to find the greatest common divisor of a pair of numbers. In a high school course, you might use the GCD to write a fraction in reduced form or in a program to efficiently draw star-shaped polygons. In this exercise we implement a well known algorithm for finding the greatest common divisor. Below is a pseudocode description of the algorithm.
Does this algorithm always reach an answer, or can it get caught in an infinite loop?
Challenge: prove by induction that the output of this algorithm really is the greatest common divisor of :N and :K.
Recall the PQGON procedure from week 5 of the semester:
TO PQGON :P :Q :SIDE REPEAT :Q [FORWARD :SIDE RIGHT (360 * (:P/:Q))] ENDWhen the fraction :P/:Q is in reduced form the total turtle turn of this procedure is 360 * :P which is the least it could possibly be and still be state transparent. When the fraction :P/:Q is improper the turtle retraces its path. Recall the question:
REPEAT :N [FORWARD :SIDE RIGHT (360 * (:P/:Q))]The answer is that :N must be :Q / (GCD :P :Q), where GCD is a LOGO procedure that outputs the greatest common denominator of two numbers.
Run PQGON or the REPEAT statement above with different values of :N, :P and :Q to convince yourself that this is true. Can you prove that this is true?
Use the Euclidean Algorithm and LOGO's REMAINDER procedure to write a program GCD :N :K that computes the greatest common divisor of two numbers :N and :K.
Use your GCD procedure to write a FASTPQGON procedure that draws the same thing that PQGON does without the turtle's having to retrace its path.