Skip to content

Instantly share code, notes, and snippets.

@kamronbatman
Created May 15, 2022 20:47
Show Gist options
  • Save kamronbatman/1291435deb4d865fedf8ddc1692d0b56 to your computer and use it in GitHub Desktop.
Save kamronbatman/1291435deb4d865fedf8ddc1692d0b56 to your computer and use it in GitHub Desktop.
Greatest Common Divisor in C# .NET 6
// Greatest Common Divisor in .NET 6
public static class Utility
{
public static uint GreatestCommonDivisor(uint u, uint v)
{
if (u == 0)
{
return v;
}
if (v == 0)
{
return u;
}
int shift = BitOperations.TrailingZeroCount(u | v);
u >>= BitOperations.TrailingZeroCount(u);
uint m;
do
{
v >>= BitOperations.TrailingZeroCount(v);
v -= u;
m = (uint)((int)v >> 31);
u += v & m;
v = (v + m) ^ m;
} while (v != 0);
return u << shift;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment