/********************************************************/ // R. A. Hillyard // reduce.cpp // Last Modified October 2001 // // Get the numerator and denominator of a positive // fraction from the user. Print it in reduces form /********************************************************/ #include<iostream> #include<cctype> using namespace std; int gcd(int x, int y); //function prototype //pre conditions: x and y have been given valid values //post conditions: will return the greatest common divisor for x and y int main() { int top = 0; //numerator int bottom = 0; //denominator int greatest = 1; //greatest common divisor char ch = 'Y'; while(true) { cout << "Enter the numerator: "; //get numerator cin >> top; cout << "Enter the denominator: "; //get denominator cin >> bottom; greatest = gcd(top,bottom); //call function //print results if(greatest == 1) cout << top << "/" << bottom << " is already reduced.\n"; else cout << "reduced form: " << top/greatest << "/" << bottom/greatest << endl;
cout << "Continue [Y/N] >"; cin >> ch; if((toupper(ch) == 'N')) break; } return 0; } /********************************************************/ // Returns the greatest common divisor of the positive integers // x and y. The Euclidean algorithm is used: // Calculate the remainder of x/y // If it's 0 the gcd is y. // Otherwise start again, replacing x with y with y with the remainder (x%y) /********************************************************/ int gcd(int x, int y) { int c; //store remainder while( (c = x%y) != 0 ) { x = y; y = c; }//end while return y; }//end of gcd