Skip to content

Commit 0178e09

Browse files
committed
added greatest common divisor test
1 parent ed0a59b commit 0178e09

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Diagnostics;
4+
using System.Linq;
5+
using System.Text;
6+
using System.Threading.Tasks;
7+
8+
namespace C_Sharp_Algorithms.AlgorithmsTests
9+
{
10+
public static class GreatestCommonDivisorTest
11+
{
12+
13+
public static void DoTest()
14+
{
15+
uint[,] testNumbers = new uint[8, 2]
16+
{
17+
{0,0 },
18+
{0,5 },
19+
{2,4 },
20+
{3,10 },
21+
{13,17 },
22+
{12,20 },
23+
{22,11 },
24+
{33,22 }
25+
};
26+
27+
for (int i = 0; i < testNumbers.GetLength(0); i++)
28+
{
29+
uint gcd = Algorithms.Numeric.GreatestCommonDivisor.FindGCD(testNumbers[i, 0], testNumbers[i, 1]);
30+
31+
if (Assert(testNumbers[i,0], testNumbers[i,1], gcd))
32+
{
33+
Console.WriteLine("{0,5}-{1,-5}: with gcd: {2,-5} : Success", testNumbers[i, 0], testNumbers[i, 1], gcd);
34+
}
35+
else
36+
{
37+
Console.WriteLine("{0,5}-{1,-5}: with gcd: {2,-5} : Error", testNumbers[i, 0], testNumbers[i, 1], gcd);
38+
}
39+
}
40+
}
41+
42+
private static bool Assert(uint a, uint b, uint gcdCandidate)
43+
{
44+
if (a == 0)
45+
return b == gcdCandidate;
46+
else if (b == 0)
47+
return a == gcdCandidate;
48+
49+
if (a % gcdCandidate != 0 || b % gcdCandidate != 0)
50+
return false;
51+
52+
//Suppose that gcdCandidate is not gcd.
53+
//With this assumption, if gcdCandidate divides both a and b then it must divide the real gcd
54+
//Namely, there should be a positive integer
55+
uint q;
56+
//such that gcd = q*gcdCandidate
57+
58+
q = 2;
59+
60+
uint _gcd = gcdCandidate * q;
61+
62+
while(_gcd < a && _gcd < b)
63+
{
64+
if (a % _gcd == 0 && b % _gcd == 0)
65+
return false;
66+
67+
_gcd *= ++q;
68+
}
69+
70+
return a > b ?
71+
((a % b == 0) && (b == gcdCandidate)) || ((a % b != 0) && (b != gcdCandidate)) :
72+
((b % a == 0) && (a == gcdCandidate)) || ((b % a != 0) && (a != gcdCandidate));
73+
}
74+
75+
}
76+
}

MainProgram/MainProgram.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
<Compile Include="AlgorithmsTests\GraphsCyclesDetectorTests.cs" />
4949
<Compile Include="AlgorithmsTests\GraphsDijkstraShortestPathsTest.cs" />
5050
<Compile Include="AlgorithmsTests\GraphsTopologicalSorterTest.cs" />
51+
<Compile Include="AlgorithmsTests\GreatestCommonDivisorTest.cs" />
5152
<Compile Include="AlgorithmsTests\HeapSorterTest.cs" />
5253
<Compile Include="AlgorithmsTests\LSDRadixSorterTest.cs" />
5354
<Compile Include="AlgorithmsTests\StringEditDistanceTest.cs" />

0 commit comments

Comments
 (0)