Euclide's Algorithm to Calculate GCD

  • Thread starter Thread starter lcam2
  • Start date Start date
  • Tags Tags
    Algorithm Gcd
Click For Summary
SUMMARY

The discussion focuses on implementing Euclid's Algorithm to calculate the Greatest Common Divisor (GCD) of two integers in C++. The user seeks guidance on how to retrieve the last non-zero remainder before reaching zero during the calculation. The provided code snippet demonstrates an incomplete implementation, highlighting the need for a loop to continuously compute the remainder until it reaches zero, ultimately returning the last non-zero value as the GCD.

PREREQUISITES
  • Understanding of C++ programming syntax and structure
  • Familiarity with functions and variable manipulation in C++
  • Knowledge of Euclid's Algorithm for GCD calculation
  • Basic concepts of control flow, specifically loops and conditionals
NEXT STEPS
  • Study the complete implementation of Euclid's Algorithm in C++
  • Learn about function prototypes and their usage in C++
  • Explore error handling and input validation in C++ programs
  • Investigate optimization techniques for GCD calculations
USEFUL FOR

Students learning C++ programming, software developers implementing mathematical algorithms, and educators teaching algorithm design and analysis.

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;
}
]
 
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;
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 24 ·
Replies
24
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 27 ·
Replies
27
Views
5K