//Greatest Common Denominator //by Daniel Blaisdell //feel free to email me //lunk@doublenegative.com //February 15, 2000 #include /**************************************** * gcd * ***************************************** * gcd(x, y) returns the greatest common* * denominator between x and y * ****************************************/ // modified by Joseph D. McLaughlin, jr. on July, 10 2000 // e-mail address poonsniff@yahoo.com // to compile on MS Visual C++ V5 // also made some grammatical corrections in user interface // added in 1.2 // iterative version, interface is designed as function and // not as procedure // fixed a bug in the loop-condition unsigned long gcd_i (unsigned long a, unsigned long b) { // both numbers have to be > 0 as gcd is only defined for // natural numbers if (!a || !b) return 0; // we know gcd if one of the numbers is zero while (a && b) { // replacing the biger number by the remainder of the // division (bigger / smaller) if (a > b) { a %= b; } else { b %= a; } } if (a) return a; else return b; } // added in 1.2 // version for n numbers // tell me in count how many elements the array number has unsigned long gcd_i_n (unsigned long count, unsigned long *number) { unsigned long result; // there's no use in calculating gcd for 0 or 1 number, though // i'm not sure if this is mathematicaly correct if (count < 2) { return 0; } result = number[0]; for (i = 1; i < count; i++) { result = gcd_i ( result, number[i] ); } return result; } /* Dan's original function int gcd(int x, int y) { if (x == 0) return y; else gcd(y%x, x); } */ // global variable added to simplify conversion int global_int = 0; // my new function v{ if(x == 0) { global_int = y; } else { gcd(y%x,x); } } void main() { int x, y; cout<<"Input first number: "; cin>>x; cout<<"Input second number: "; cin>>y; // moved gcd function call to seperate line gcd(x,y); // replaced gcd function call in this line // with the value of the global variable cout<< global_int <<" is the greatest common denominator."<