Solved

Greatest Common Factor Function

Posted on 1997-04-16
1
745 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
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Eclipse IDE - Cannot copy/paste from console output 8 305
Problem with SqlConnection 4 184
How to Correctly derive class from CWinThread in MFC 4 88
Coding for the first time 9 62
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
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.

680 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