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.
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