Skip to content

Instantly share code, notes, and snippets.

@wanderrful
Created May 4, 2012 06:13
Show Gist options
  • Save wanderrful/2592498 to your computer and use it in GitHub Desktop.
Save wanderrful/2592498 to your computer and use it in GitHub Desktop.
Euclidean Algorithm in C++
=begin
I found this randomly and wanted to save it for future reference.
Let a, b denote the numerator and denomator, respectively. Let 'gcd' denote the Greatest Common Divisor of both a and b.
=end
if(a==0 || b==0)
return gcd = 1;
else
{
r = (a%b);
while ( r < 0 || r > 0)
{
a = b;
b = r;
r = (a%b);
}
gcd = b;
}
return gcd;
@NoorEldali
Copy link

@wanderrful

if(a==0 || b==0)
             return gcd =  1;

The code above returns gcd as 1 if either a or b =0 right?
but please take a look at this:

If k is a non-zero integer, then k divides zero. ... So gcd(k, 0) = gcd(0,k) = k. However, gcd(0, 0) isn't defined. All integers are common divisors of 0 and 0, so there is no greatest one.

source:
http://mfleck.cs.illinois.edu/building-blocks/version-1.0/number-theory.pdf
thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment