Confused on a code from a Professor, Greatest Common Divisor

I'm confused about how a certain algorithm works. My professor gave it to us as part of an example code, but I am not sure how it runs or why I need to use it.

int gcm(int a,int b)
{
int g;
a = fabs(a);
b = fabs(b);
int r = a%b;
if(a == 0 || b == 0)
return 1;
while(r!=0)
{
a = b;
b = r;
r = a%b;
}
return b;
}
It is to be used in a code to add fractions, but I am confused why this is necessary and how and why this algorithm works. I was trying to use:

Fraction add(const Fraction& f) const
{
Fraction answer;
answer.top = (top*f.bottom)+(f.top*bottom);
answer.bottom = (bottom*f.bottom);
return answer;
}//a constructor within Faction class, which holds two ints, top and bottom and passes two inputs into a constructor in the class.

This method is called f1.add(f2) or what I name the objects in the class. I call a method with the first object then pass the second into the method. I am wondering why I need to use the gcm code given by the professor.

Fraction add(const Fraction& f) const
{
Fraction answer;
answer.top = (top*f.bottom)+(f.top*bottom);
answer.bottom = (bottom*f.bottom);
int g = gcm(answer.top, answer.bottom);
answer.top = answer.top/g;
answer.bottom = answer.bottom/g;
return answer;
}

If anyone could at least explain how the algorithm works, I would be grateful.
> but I am confused why this is necessary

The idea is to reduce the fraction to a minimal form.
For instance, if we have 42/24. gcd of 42 and 24 is 6, dividing both the numerator and the denominator by the gcd, we get the equivalent 7/4.

> If anyone could at least explain how the algorithm works

See the proof of validity, worked example and visualization here:
http://en.wikipedia.org/wiki/Euclidean_algorithm#Description
Topic archived. No new replies allowed.