CS 210 - Fundamentals of Programming I

Spring 2006 - In-class exercise for 4/13/06

10 points

Names:

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.

Problem Statement

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.

Main Program

Function: GCD

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:

a.
What makes Euclid's algorithm a recursive algorithm?

b.
What is the base (or anchor) case of the algorithm?

c.
What are the recursive (or inductive) cases of the algorithm?

d.
What is the greatest common divisor of 24 and 84?

e.
On the back of this sheet, draw a trace (as demonstrated in class) of the function call GCD(24,84).

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.


Converted using latex2html on Wed Apr 12 23:16:42 CDT 2006