Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Greatest Common Factor Function

Posted on 1997-04-16
1
Medium Priority
?
757 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 200 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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

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…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
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.

688 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