Spring 2006 - In-class exercise for 4/13/06
10 points
This exercise should be completed in pairs. The purpose of this exercise is to gain experience writing recursive functions. Here is a problem statement, analysis, and design for today's exercise.
For some applications, we need to find the greatest common divisor of two positive integers, that is, the largest integer that divides both numbers. (One number q divides another number p if there is no remainder from p/q. In C++ code, this would mean that p % q == 0.) The Greek mathematician Euclid devised the following recursive algorithm to compute the greatest common divisor (GCD) of two numbers, m and n.
This algorithm states that if n is the smaller number and n divides m, then the GCD is n. If m is the smaller number, then the GCD determination should be performed with the arguments reversed. Otherwise, if n does not divide m, the answer is obtained by finding the GCD of n and the remainder of m divided by n.
Write a program that asks the user for two positive integers and computes the greatest common divisor of the two integers. The greatest common divisor should be computed using a function that implements Euclid's algorithm given above.
| Objects | Type | Kind | Name |
| first positive integer | int | variable | num1 |
| second positive integer | int | variable | num2 |
| greatest common divisor | int | variable | --- |
| Objects | Type | Kind | Movement | Name |
| first positive integer | int | variable | received | m |
| second positive integer | int | variable | received | n |
| greatest common divisor | int | variable | returned | --- |
0. Create a new project, then download file inclass23.cpp from the course webpage under today's date to your project folder. This program is an implementation of the main program that will read in two input values and call the function GCD with the two values.
1. (5 points) Add the prototype and a definition for the
GCD function that uses Euclid's algorithm to compute the
greatest common divisor of the two input values. Note that this
recursive algorithm is a little different than the ones we saw earlier
in class, since it has two recursive cases, so you'll have to have an
extra test to determine which case should be followed. Build and run
this program.
2. (5 points) When you are confident your program works
correctly, answer the following questions:
Note that you can put a cout statement at the very beginning of your GCD function to print out the values of m and n to check your trace.
When you have completed this exercise, print out your program
file and turn it in with one copy of this exercise sheet with your
answers to the questions.