GCD using Euclidean Algorithm

bracketslash

Registered User
Joined
Feb 6, 2013
Messages
224
For a recent assignment in my C/C++ programming course at university, we were instructed to ask the user for two non-zero positive integers, and then calculate the greatest common divisor of those two non-zero positive integers using the Euclidean algorithm.

After lots of writing and discussions with my other math peers, we came up with the following solution:

Code:
#include <iostream>

using namespace std;

int main() {
  int a = 40, b = 25, z;
  while ( b > 0 ) { // while the second integer is greater than 0
    z = b;          // set a third variable to the current value of the second integer
    b = a % b;      // find the remainder of the first integer and the second integer, and then set that as the second integer
    a = z;          // set the first integer to be the value of the previous second integer
  }
  cout << a << endl; // once the remainder (b) of a and b is 0, the GCD is a
  return 0;
}

A pretty fun learning experience. Applying mathematics like the Euclidean algorithm to programming is intriguing, in my opinion, as it enables you to perform mathematical equations much faster than writing. :-P
 
How long have you been programming for?
 
Just curious. Programming fascinates me, I just can't do it worth a shit :).
 
Just curious. Programming fascinates me, I just can't do it worth a shit :).

I'm not very good either, which is why it took so long to figure this out!

It's so weird that we can make a group of transistors solve rk−2 = qk rk−1 + rk. Systematically. Intriguing. :-)
 
Back
Top