18 Star 133 Fork 63

编程语言算法集 / C-Sharp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
BinaryGreatestCommonDivisorFinder.cs 1.61 KB
一键复制 编辑 原始数据 按行查看 历史
Gerson Jr 提交于 2023-12-30 10:33 . Switch to file-scoped namespaces (#430)
using System;
namespace Algorithms.Numeric.GreatestCommonDivisor;
/// <summary>
/// Finds greatest common divisor for numbers u and v
/// using binary algorithm.
/// Wiki: https://en.wikipedia.org/wiki/Binary_GCD_algorithm.
/// </summary>
public class BinaryGreatestCommonDivisorFinder : IGreatestCommonDivisorFinder
{
public int FindGcd(int u, int v)
{
// GCD(0, 0) = 0
if (u == 0 && v == 0)
{
return 0;
}
// GCD(0, v) = v; GCD(u, 0) = u
if (u == 0 || v == 0)
{
return u + v;
}
// GCD(-a, -b) = GCD(-a, b) = GCD(a, -b) = GCD(a, b)
u = Math.Sign(u) * u;
v = Math.Sign(v) * v;
// Let shift := lg K, where K is the greatest power of 2 dividing both u and v
var shift = 0;
while (((u | v) & 1) == 0)
{
u >>= 1;
v >>= 1;
shift++;
}
while ((u & 1) == 0)
{
u >>= 1;
}
// From here on, u is always odd
do
{
// Remove all factors of 2 in v as they are not common
// v is not zero, so while will terminate
while ((v & 1) == 0)
{
v >>= 1;
}
// Now u and v are both odd. Swap if necessary so u <= v,
if (u > v)
{
var t = v;
v = u;
u = t;
}
// Here v >= u and v - u is even
v -= u;
}
while (v != 0);
// Restore common factors of 2
return u << shift;
}
}
C#
1
https://gitee.com/TheAlgorithms/C-Sharp.git
git@gitee.com:TheAlgorithms/C-Sharp.git
TheAlgorithms
C-Sharp
C-Sharp
master

搜索帮助