代码拉取完成,页面将自动刷新
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;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。