Write a function named "reduce" that takes two positive integer arguments, call them "num" and "demon", treats them as the numerator and denominator of a fraction, and reduces the fraction. That is to say, each of the two argument will be modified by dividing it by the greatest common divisor of the two integer. The function should return the value 0(to indicate the failure reduce) if either of the two argument is zero or negative and should return the value 1 otherwise.
#include <iostream>
using namespace std;
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return (b, a%b);
}
int reduce(int& num, int& denom) {
if (num <= 0 || denom <= 0 ) {
return 0;
}
int divisor = gcd(num, denom);
num /= divisor;
denom /= divisor;
return 1;
}
int main() {
int num, denom, res;
cout << "Enter num: ";
cin >> num;
cout << "Enter denom: ";
cin >> denom;
res = reduce(num, denom);
cout << "res = " << res << endl;
cout << num << "/" << denom << endl;
return 0;
}
Comments
Leave a comment