Solved

Greatest Common Factor Function

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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
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 additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

744 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now