Euclid's Algortithm

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, im not sure it is right, i honestly don't understand how to use functions. Ill appreciate any help and also any extra information in how to write and use functions. Thanks in advance.

//Euclid's Algorithm

#include <iostream>

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

int main ()
{
int a, b;

cout << "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;

if ( a > b)
{
x = a;
a = b;
b = x;

remainder = a;

while (remainder != 0)
{
x = remainder;
remainder = b % remainder;
b = x;
}
cout << "GCD is " << r << endl;
}

if (b > a)
{
x = b;
b = a;
a = x;

remainder = b;

while (remainder != 0)
{
x = remainder;
remainder = a % remainder;
a = x;
}
cout << "GCD is " << r << endl;
}
}
First thing I notice is where is r declared?
Second what your algorythm is doing is simply moding the remainder of the largest number.
So
1
2
3
4
5
6
7
int r; 
if (A > B)
  r = b;
  r %= A
else
  r = A;
  r %= B;



Hi:
Thanks for your time and help. Using your code i am getting a remainder of zero. How can i print the last non zero value?
Thanks in advance, here is my new code.
[

#include <iostream>

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

int main ()
{
int a, b;

cout << "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 r, remainder;
remainder = 0;


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

cout << r << endl;
}
]
Well, with the first code you posted, within the if statement if ( a > b), if you put cout << "GCD is " << b << endl; and in the other if statement, if you put cout << "GCD is " << a << endl;, then you get correct results. However, you're missing the case for when a == b.

From the looks of it, it seems like you can write and use functions fine. You have the function "remainder" being called correctly from within the main function. Although I would rename the function to "GCD" as that's what it computes. You might also consider having it return the GCD as an int and have the main function output the result to the console.
Topic archived. No new replies allowed.