forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryGreatestCommonDivisorFinder.cs
70 lines (60 loc) · 1.61 KB
/
BinaryGreatestCommonDivisorFinder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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;
}
}