Skip to content

Instantly share code, notes, and snippets.

@AmirMahdyJebreily
Last active September 3, 2024 21:29
Show Gist options
  • Save AmirMahdyJebreily/2c0e7c05f642af18c3bd6d58a915bfdc to your computer and use it in GitHub Desktop.
Save AmirMahdyJebreily/2c0e7c05f642af18c3bd6d58a915bfdc to your computer and use it in GitHub Desktop.
Euclidean algorithm for GCD in C# By CodeAgha
Euclidean algorithm for GCD in C# By CodeAgha
The parenthesis is the GCD (Greatest common factor) sign and the 'mod' symbol is equal to the remainder of the division.
In any case, we write the smaller number first and the larger number second
Proof from division theorem
a/b => a = bq + r
v != 0 | gcd(u, v) = gcd(v, u mod v)
gcd(u, u) = u
gcd(u, 0) = |u|
- examples :
gcd(12, 30) = gcd(12, 30 mod 12) = gcd(6, 12) = gcd(6, 12 mod 6) = gcd(6, 6) = 6
gcd(18, 48) = gcd(18, 48 mod 18) = gcd(12, 18) = gcd(12, 18 mod 12) = gcd(6, 12) = gcd(6 , 12 mod 6) = gcd(6, 6) = 6
gcd(9, 24) = gcd(9, 24 mod 9) = gcd(6, 9) = gcd(6, 9 mod 6) = gcd(3, 6) = gcd(3, 6 mod 3) = gcd(3, 0) = |3| = 3
// long and simple write :
int gcd(int u, int v)
{
if (v != 0)
{
return gcd(v, u % v);
}
return u;
}
// short and complex write :
int gcd(int u, int v) => ((v != 0) ? gcd(v, u % v) : u);
package euclideanGCD
func gcd(n int, v int) int {
if v == 0 {
return n
}
return gdc(v, n%v)
}
def gcd(u,v):
return gcd(v, u % v) if (v != 0) else u
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment