We help IT Professionals succeed at work.

# gcd problem

on
I am trying to build a recursive gcd (number1, number2) function and I think I have most of it.
However, the directions say that number1 must always be larger then number2.  I believe I have this too, ut when I was running my test plan I came across a snag.

I am not sure if I have done this correctly... because when I enter gcd(73,73) there is no output.  Any ideas on what I'm missing?  Also I am not sure if it is exchanging the two integers when number2 is larger??!!!!!

``````int gcd (int number1, int number2)
{
if (number1 % number2 == 0)
return number2;
else
return gcd (number2, number1 % number2);

}

int main ()
{
//introduce myself
cout << "Project 1: Exercise 6.45  Created by Ali Ideus-Balboa" << endl;
cout << "Determine the GCD of two integers where number1 is always larger then number2. " << endl;
cout << endl;

int number1;	//declare first integer value
int number2;	//declare second integer value

cout << "Enter he first number (integer): ";	//read in first integer input by user
cin >> number1;
cout << "Entr the second number (integer): ";	//read in second integer input by user
cin >> number2;

if (number1 == number2)		//swap number1 and number2 if first number is not greater
return number1;
if (number1 < number2)
number2 = number2 - number1;
else
number1 = number1 - number2;	//at this point number1 will always be >= number2

cout << gcd(number1, number2) << endl;
}
``````
Comment
Watch Question

## View Solution Only

BRONZE EXPERT
Top Expert 2009
Commented:
>>         if (number1 == number2)         //swap number1 and number2 if first number is not greater
>>                 return number1;

You don't need this. Your gcd function already correctly handles the situation where number1 == number2. Just get rid of these two lines.

>>         if (number1 < number2)
>>                 number2 = number2 - number1;
>>         else
>>                 number1 = number1 - number2;    //at this point number1 will always be >= number2

This is not a good way to swap. Swapping is usually done like this :

if (number1 < number2) {
int tmp = number1;
number1 = number2;
number2 = tmp;
}

Commented:
Thanks!!!!  Again!!!!!!!!!!!