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.
#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";
}
}
Comments
Leave a comment