We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

# Greatest Common Factor Function

on
Medium Priority
817 Views
I am attempting to write a C++ function that evalutes two integers and calculates their greatest common factor(Once using a post test loop and once using a pretest loop, so two examples!).  I have been generally succesful, but in some instances my function has failed.  How would you write such a function and implement error checking for two int's with no common factor?
Comment
Watch Question

## View Solution Only

Commented:
ANY two integers ALWAYS have a greatest common divisor.
(Sometimes, it equals one.)

int gcd(int a, int b)
{
if (a < 0)
a = -a;
if (b < 0)
b = -b;

while (a != 0 && b != 0)
if (a < b)
b %= a;
else
a %= b;

return a + b;
}

Not the solution you were looking for? Getting a personalized solution is easy.

##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile