Advertisement
Nikmosi

BinaryEuclideanAlgorithm

Dec 15th, 2020 (edited)
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.68 KB | None | 0 0
  1. /// <summary>
  2. /// Находит НОД с помощью Бинарного алгоритма Евклида.
  3. /// </summary>
  4. /// <param name="a"></param>
  5. /// <param name="b"></param>
  6. /// <returns></returns>
  7. public static long GcdBinaryEuclideanAlgorithm(long a, long b)
  8. {
  9.     if (a == 0 || b == 0 || a == b)
  10.         return a > 0 ? a : b;
  11.     if ((a & 1) == 0 && (b & 1) == 0)
  12.         return 2 * GcdBinaryEuclideanAlgorithm(a >> 1, b >> 1);
  13.     if ((a & 1) == 0)
  14.         return GcdBinaryEuclideanAlgorithm(a >> 1, b);
  15.     if ((b & 1) == 0)
  16.         return GcdBinaryEuclideanAlgorithm(a, b >> 1);
  17.     if (a > b)
  18.         return GcdBinaryEuclideanAlgorithm((a - b) >> 1, b);
  19.     return GcdBinaryEuclideanAlgorithm(a, (b - a) >> 1);
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement