Answer to Question #174943 in C++ for Pali

Question #174943

Write a function named "reduce" that takes two positive integer arguments, call them "num" and "denom", treats them as the numerator and denominator of a fraction, and reduces the fraction. That is to say, each of the two arguments will be modified by dividing it by the greatest common divisor of the two integers. The function should return the value 0 (to indicate failure to reduce) if either of the two arguments is zero or negative, and should return the value 1 otherwise.


1
Expert's answer
2021-03-24T04:00:13-0400
#include <iostream>

using namespace std;

long long gcd(long long a, long long b)
{
  if (a % b == 0)
    return b;
  if (b % a == 0)
    return a;
  if (a > b)
    return gcd(a % b, b);
  else
    return gcd(a, b % a);
}

int reduce(long long &num, long long &denom)
{
    long long gcdFrac;
    if ((gcdFrac = gcd(num, denom)) != 1)
    {
        num /= gcdFrac;
        denom /= gcdFrac;
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    long long num, denom;
    cout << "Enter numerator: ";
    cin >> num;
    cout << "Enter denominator: ";
    cin >> denom;
    if (reduce(num, denom))
    {
        cout << "Reduced fraction is " << num << "/" << denom;
    }
    else
    {
        cout << "Fraction " << num << "/" << denom << " can not be reduced";
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS