Euclide's Algorithm to Calculate GCD

1 reply · 2K views · last reply
lcam2
Messages
28
Reaction score
0

Homework Statement


Using Euclid's algorithm write a program with a function that determines and returns the GCD of two integer arguments.

This is what i wrote, when i print the remainder is zero, How can i get the last remaninder before the zero value? :confused:

Thanks

Homework Equations





The Attempt at a Solution



[

#include <iostream>

using namespace std;
void remainder ( int, int); //Function Prototype

int main ()
{
int a, b;

count << "This Program calculates the GCD of two integers \n"
<< "Please enter two integers" << endl;
cin >> a >> b;

remainder (a, b); //Calling the Function


return 0;

}

void remainder ( int a, int b) //Remainder function
{
int x, remainder;
remainder = 0;

int r;
if (a > b)
{r = b;
r %= b;
}
else
{r = a;
r %= b;
}

count << r << endl;
}
]
 
You need to repeat the process until the remainder is zero and then output the other variable. For example, something like the following code should output gcd(a,b) correctly.

Code:
int r;

if (a > b)
  { r = a;
    a = b;
    b = r
  }while (a !=0)
  { r = a;
    a = b % a;
    b = r
  }

cout << b << endl;