QUOTE (zach101 @ Dec 9 2005, 07:23 PM)

Okay i got a little further take a llook at this code and tell me what you think do i need a while loop in there?
I'd do it a little more like this:
CODE
#include <iostream>
using namespace std;
int gcd(int m, int n)
{
if(n == 0)
return m;
else
gcd(n, m % n);
}
void reduce(int &num, int &denom)
{
int divisor = gcd(num, denom);
num /= divisor;
denom /= divisor;
}
int main()
{
int num = 0, denom = 0;
cout << "Enter the numerator: ";
cin >> num;
cout << "Enter the denominator: ";
cin >> denom;
reduce(num, denom);
cout << "The reduced fraction is " << Num << "/" << Denom << endl;
return 0;
}
A few things to note:
- you had a few lines without a semicolon that really needed one.
- C++ headers don't end in .h, and the line "using namespace std;" should be used afterwards.
- functions, if statements, and loops that contain more than one line of code need to have that code contained within braces. {}
- it is C++ convention to name your variables in lower case.
- the statement "Div % Div == 0" is unnecessary as a number will always evenly divide into itself.
- in your original posted code, you had an if statement using =. In C++, this is the assignment operator. The equal to operator is ==.
QUOTE (methane @ Feb 19 2006, 12:22 PM)

To find out the GCD/GCF of two integers, you can make use of euclidean algorithm. That is, GCD(a,b ) = GCD(a%b,b ) if a>b. You can use a recursive function to find out the answer in fewer steps. The function should look like this
CODE
int GCD(int a , int b)
{
if (a == b)
{
return a;
}
if (a * b == 0)
{
return a + b;
}
return ( a%b , b%a);
}
Hope it can help.
Generally the code can be written much cleaner, not to mention the function you wrote is not recursive. The following code should work just as nicely:
CODE
int gcd(int m, int n)
{
if(n == 0)
return m;
else
gcd(n, m % n);
}
Comment/Reply (w/o sign-up)