Lesson goal: The GCD and reducing fractions to lowest terms

Previous: Finding the Greatest Common Divisor (GCD) | Home | Next: A better GCD calculator

In this last lesson, we developed a function that will find the GCD of two numbers. It turns out when you "reduce a fraction to lowest terms," you are really dividing both the numerator and denominator by the GCD. So we'll do that here: program a simple "fraction reducer" using the GCD function from the last lesson.

But, there's a small issue. Remember in the gcd(a,b) function that the first argument (a) must be less than the second argument (b). To be sure our fraction reducer will always work, let's write a "wrapper function" called get_gcd that will ensure that the main gcd function gets called with the lower number first.

Now you try. Fix the if statement to compare a and b, and the two gcd function calls to ensure that gcd(a,b) always gets called with $a< b$.

Type your code here:


See your results here:

This code will not run! You have to do two things. First, figure out what condition you'll put in the if statement to check on the relative size of a vs. b. Next, given the answer to your condition, in what order will you place a and b in the gcd calls? It'll be either gcd(a,b) or gcd(b,a). See if you can figure out which goes where. Dismiss.
Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.