Euclide's Algorithm to Calculate GCD

  • Thread starter Thread starter lcam2
  • Start date Start date
  • Tags Tags
    Algorithm Gcd
AI Thread Summary
Euclid's algorithm is used to calculate the GCD of two integers by repeatedly finding the remainder until it reaches zero. The provided code attempts to implement this but fails to correctly track the last non-zero remainder. To fix this, the code should use a loop that continues until one of the integers becomes zero, while updating the other integer as the GCD. The final output should be the non-zero integer when the loop ends. Properly implementing this logic will yield the correct GCD result.
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;

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;

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

cout << r << endl;
}
]
 
Physics news on Phys.org
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;
 
Back
Top