Finding the GCD of Two integers

Hey, I'm new here, and because I've create this account, is to learn from others based on their opinions and suggestions. Now, I'm studying computer engineering and I'm learning how to programming in C++ language as introduction. And I've this program... I'm working on "functions", in my code I've 4 CPP files and 3 headers, and I want to get the gcd of two integers.

The problem is :

First of all, I've read the euclid's theorem, and I understand it, but...

Let's see :

// A program that obtain the result gcd of two integers.

#include <iostream>
#include <iomanip>


using namespace std;


int gcd( int a, int b);

int main() {

int a, b;

cout << "Enter two integers: ";
cin >> a >> b;

cout << "The greatest common divisor of" << a << "and" << b << "is" <<
gcd(a, b) << endl;


return(0);

}

int gcd( int a, int b) {

int r1, c;


while ( a >= b || a <= b ) {

r1 = a % b;
c = r1

if ( r1 == 0 ) {

return(a);
}

else
{

return(b);


}
}
}

I just want to learn and see your opinions about this. Thank You.
Please use [code] [/code] tags -- they make your code look a lot nicer. (It's the <> button under the format options)

What problem are you having?

A typical GCD function looks something like this (I think):
1
2
3
4
5
6
7
8
9
10
int gcd(int a, int b)
{
    while (b != 0)
    {
        int tmp = a;
        a = b;
        b = tmp % b;
    }
    return a;
}

Compare that to what you have.
Thanks for the help. I've already try what you're suggesting, but somehow it won't work... Maybe I was wrong, but then I decided to try once! Again! And this is what I got :

int gcd( int a, int b) {

int r;

while ( a > b || a < b ) {

r = a % b;
a = b;
b = r;

if ( r == 0 ) {

return(b);

} else
{

r = b % a;
b = a;
a = r;

return(a);

}
}
}

And wow, I'm very excited... For now :-) thanks for your time, I appreciated.
The format, well, sorry I forgot it xD
What if a == b? You don't return any value in that case.
Perhaps it would be better if you spend some time reading this short description of the algorithm (and enclosed pseudo-code).

http://codeabbey.com/index/wiki/gcd-and-lcm

This task is simple but it is crucial to have a clear understanding of what you are doing and I'm not sure you have :)
The format, well, sorry I forgot it xD


There's nothing stopping you from editing your post to put the formatting in.
Topic archived. No new replies allowed.