forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GreatestCommonDivisor.cs
70 lines (60 loc) · 1.6 KB
/
GreatestCommonDivisor.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
{
public static class GreatestCommonDivisor
{
/// <summary>
/// Returns the greatest common divisor of two numbers using Euclidean Algorithm.
/// </summary>
public static int FindGCDEuclidean(int a, int b)
{
int t = 0;
a = Math.Abs(a);
b = Math.Abs(b);
if (a == 0)
return b;
if (b == 0)
return a;
while (a % b != 0) {
t = b;
b = a % b;
a = t;
}
return b;
}
/// <summary>
/// Returns the greatest common divisor of two numbers using Stein Algorithm.
/// </summary>
public static int FindGCDStein(int a, int b)
{
a = Math.Abs(a);
b = Math.Abs(b);
return Stein(a, b);
}
private static int Stein(int a, int b)
{
if (a == 0)
return b;
if (b == 0)
return a;
if (a == b)
return a;
if ((~a & 1) == 1)
{
if ((b & 1) == 1)
{
return Stein(a >> 1, b);
}
else
{
return Stein(a >> 1, b >> 1) << 1;
}
}
if ((~b & 1) == 1)
{
return Stein(a, b >> 1);
}
return a > b ? Stein((a - b) >> 1, b) : Stein(a, (b - a) >> 1);
}
}
}