Solved

Greatest Common Factor Function

Posted on 1997-04-16
1
748 Views
Last Modified: 2012-06-21
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?
0
Comment
Question by:matlurz
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 2

Accepted Solution

by:
mlev earned 100 total points
ID: 1162759
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;
}

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question