|
1 | | -/*** |
2 | | - * Euclidean Algorithm to find the greatest common divisor of two numbers. |
3 | | - * |
4 | | - */ |
5 | | - |
| 1 | +using System; |
6 | 2 |
|
7 | 3 | namespace Algorithms.Numeric |
8 | 4 | { |
9 | 5 | public static class GreatestCommonDivisor |
10 | 6 | { |
11 | 7 | /// <summary> |
12 | | - /// Finds and returns the greatest common divisor of two numbers |
| 8 | + /// Returns the greatest common divisor of two numbers using Euclidean Algorithm. |
13 | 9 | /// </summary> |
14 | | - public static uint FindGCD(uint a, uint b) |
| 10 | + public static int FindGCDEuclidean(int a, int b) |
15 | 11 | { |
| 12 | + a = Math.Abs(a); |
| 13 | + b = Math.Abs(b); |
| 14 | + |
16 | 15 | if (a == 0) |
17 | 16 | return b; |
18 | 17 | if (b == 0) |
19 | 18 | return a; |
| 19 | + if (a == b) |
| 20 | + return a; |
20 | 21 |
|
21 | | - uint _a = a, _b = b; |
22 | | - |
23 | | - //Bitwise operator '&' works on individual bits of each value |
24 | | - //result is 0 or 1 |
25 | | - //it works like a modulus operator '%' but is more efficient |
26 | | - uint r = _a & _b; |
| 22 | + return Euclidean(a, b); |
| 23 | + } |
27 | 24 |
|
28 | | - while(r != 0) |
29 | | - { |
30 | | - _a = _b; |
31 | | - _b = r; |
32 | | - r = _a & _b; |
33 | | - } |
| 25 | + private static int Euclidean(int a, int b) |
| 26 | + { |
| 27 | + if (b == 0) |
| 28 | + return a; |
34 | 29 |
|
35 | | - return _b; |
| 30 | + return Euclidean(b, a % b); |
36 | 31 | } |
37 | 32 |
|
38 | 33 | /// <summary> |
39 | | - /// Determines given two numbers are relatively prime |
| 34 | + /// Returns the greatest common divisor of two numbers using Stein Algorithm. |
40 | 35 | /// </summary> |
41 | | - public static bool IsRelativelyPrime(uint a, uint b) |
| 36 | + public static int FindGCDStein(int a, int b) |
| 37 | + { |
| 38 | + a = Math.Abs(a); |
| 39 | + b = Math.Abs(b); |
| 40 | + |
| 41 | + return Stein(a, b); |
| 42 | + } |
| 43 | + |
| 44 | + private static int Stein(int a, int b) |
42 | 45 | { |
43 | | - return FindGCD(a, b) == 1; |
| 46 | + if (a == 0) |
| 47 | + return b; |
| 48 | + if (b == 0) |
| 49 | + return a; |
| 50 | + if (a == b) |
| 51 | + return a; |
| 52 | + |
| 53 | + if ((~a & 1) == 1) |
| 54 | + { |
| 55 | + if ((b & 1) == 1) |
| 56 | + { |
| 57 | + return Stein(a >> 1, b); |
| 58 | + } |
| 59 | + else |
| 60 | + { |
| 61 | + return Stein(a >> 1, b >> 1) << 1; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + if ((~b & 1) == 1) |
| 66 | + { |
| 67 | + return Stein(a, b >> 1); |
| 68 | + } |
| 69 | + |
| 70 | + return a > b ? Stein((a - b) >> 1, b) : Stein(a, (b - a) >> 1); |
44 | 71 | } |
45 | 72 | } |
46 | 73 | } |
0 commit comments