forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GreatestCommonDivisor.cs
46 lines (39 loc) · 1.09 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
/***
* Euclidean Algorithm to find the greatest common divisor of two numbers.
*
*/
namespace Algorithms.Numeric
{
public static class GreatestCommonDivisor
{
/// <summary>
/// Finds and returns the greatest common divisor of two numbers
/// </summary>
public static uint FindGCD(uint a, uint b)
{
if (a == 0)
return b;
else if (b == 0)
return a;
uint _a = a, _b = b;
//Bitwise operator '&' works on individual bits of each value
//result is 0 or 1
//it works like a modulus operator '%' but is more efficient
uint r = _a & _b;
while(r != 0)
{
_a = _b;
_b = r;
r = _a & _b;
}
return _b;
}
/// <summary>
/// Determines given two numbers are relatively prime
/// </summary>
public static bool IsRelativelyPrime(uint a, uint b)
{
return FindGCD(a, b) == 1;
}
}
}