Created
May 15, 2022 20:47
-
-
Save kamronbatman/1291435deb4d865fedf8ddc1692d0b56 to your computer and use it in GitHub Desktop.
Greatest Common Divisor in C# .NET 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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