Homework 17 Solution

 

Write a program that reads in a list of fractions from the user, each separated by commas and the whole terminated by a semicolon, prints out the ones that are not in lowest terms. For example, a typical run might look like this (user input shown in red):

2/4, 6/9, 3/11, 21/5, 8/10;
2/4 is not in lowest terms!
6/9 is not in lowest terms!
8/10 is not in lowest terms!

In writing this program, define and use a function int gcd(int,int); that takes two positive integers and returns their greatest common divisor. (Check out Class 10 to remind yourself about computing gcd's.) Turn In a printout of your program along with a screen capture showing your program running on the above input.

Solution

// KGS
// Hmwk 17


#include <iostream>
using namespace
std;

// prototype
int gcd(int,int);

int main (){
    int numerator,denominator,lowest;
    char separator;

    cout << "Enter a list of common fractions separated by commas"
        << " and terminated with a ;" << endl;
    do {
        cin >> numerator >> separator >> denominator >> separator;
        lowest = gcd(numerator,denominator);
        if (lowest != 1)
            cout << numerator << '/' << denominator
                << " is not in lowest terms!" << endl;
    } while (separator != ';');

    return 0;
}


int gcd (int num, int den){
    int a, b, r;
    if (num >= den) {
        a = num;
        b = den;
    }
    else {
        a = den;
        b = num;
    }
    while (b != 0){
        r = a % b; // remember "%" is remainder
        a = b;
        b = r;
    }
    return a;
}