# Thread: Greatest Common Divisor problem

1. ## Greatest Common Divisor problem

I'm having trouble with creating a program that calculates the greatest common divisor between two numbers. I would greatly appreciate some help.

Code:
```#include <iostream>

using std::cout;
using std::cin;
using std::endl;

double gcd ( int x, int y );

int main()
{
int a;
int b;

// allow the five sets of numbers to be input
for ( int j = 1; j <= 5; ++j ) {
cout << "Enter two integers: ";
cin >> a >> b;
cout << "The greatest common divisor of " << a
<< " and " << b << " is "
<< gcd ( a, b ) << "\n\n";

} // end for

return 0;

} // end main

// function gcd definition
double gcd( int x, int y )
{
int greatest = 1;

for ( int i = 2; i <= ( ( x < y ) ? x : y ); ++i );

if  0 = ( x % i ) + ( y % 1 );
greatest = i;

return greatest;

} // end function gcd```

2. You didn't say what the problem was. A compiler error? Bad output?

I would look at this line first (that's not how you do an if test for equality):
Code:
`if 0 = ( x % i ) + ( y % 1 );`

3. that, and the semicolon at the end of for(...) is a problem... and you should really use curly braces there... other than that, It's fine (I didn't really check for logic errors, but that looks okay)

the only thing I'd suggest is letting people exit your program somehow...

Code:
```double gcd( int x, int y )
{
int greatest = 1;

for ( int i = 2; i <= ( ( x < y ) ? x : y ); ++i )
{

if ( 0 == ( x % i ) + ( y % 1 ))
greatest = i;
}

return greatest;

} // end function gcd```

4. nevermind im not paying attention,

5. that way works too... with a little modification... or you could also do:
Code:
`if(!((x%i)+(y%1)));`
although I wouldn't.

6. This code makes no sense. y % 1 evaluates to zero. Always.

Fenix, you need to learn your C++ syntax before anything else.

7. must be a typo, sure they ment, 'i' there to

8. I worked on it some more and it still has problems. It won't calculate the greatest common divisor. No matter what it always comes up with the lowest of the two numbers. What needs to be fixed?
Code:
```#include <iostream>

using std::cout;
using std::cin;
using std::endl;

double gcd ( int x, int y );

int main()
{
int a;
int b;

// allow the five sets of numbers to be input
for ( int j = 1; j <= 5; ++j ) {
cout << "Enter two integers: ";
cin >> a >> b;
cout << "The greatest common divisor of " << a
<< " and " << b << " is "
<< gcd ( a, b ) << "\n\n";

} // end for

return 0;

} // end main

// function gcd definition
double gcd( int x, int y )
{
int greatest = 1;

for ( int i = 2; i <= ( ( x < y ) ? x : y ); ++i )
{

if ( 0 == ( x % i ) + ( y % i ));
greatest = i;
}

return greatest;

} // end function gcd```

9. You forgot to remove the semi-colon after the if statement.