Skip to content

Commit 068f65a

Browse files
make gcd() not recursive
1 parent 50edb33 commit 068f65a

File tree

3 files changed

+41
-4
lines changed

3 files changed

+41
-4
lines changed

CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ enable_testing()
8989
add_executable(ToolsTest src/ToolsTest.cc)
9090
target_link_libraries(ToolsTest phosg)
9191

92-
foreach(TestName IN ITEMS ArgumentsTest EncodingTest FilesystemTest HashTest ImageTest JSONTest KDTreeTest LRUMapTest LRUSetTest ProcessTest StringsTest TimeTest UnitTestTest)
92+
foreach(TestName IN ITEMS ArgumentsTest EncodingTest FilesystemTest HashTest ImageTest JSONTest KDTreeTest LRUMapTest LRUSetTest MathTest ProcessTest StringsTest TimeTest UnitTestTest)
9393
add_executable(${TestName} src/${TestName}.cc)
9494
target_link_libraries(${TestName} phosg)
9595
add_test(NAME ${TestName} COMMAND ${TestName})

src/Math.hh

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
1+
#include <string>
12
#include <utility>
3+
#include <vector>
4+
5+
#include "Encoding.hh"
26

37
namespace phosg {
48

59
template <typename IntT>
610
constexpr IntT gcd(IntT a, IntT b) {
7-
if (b == 0) {
8-
return a;
11+
while (b != 0) {
12+
IntT m = a % b;
13+
a = b;
14+
b = m;
915
}
10-
return gcd(b, a % b);
16+
return a;
1117
}
1218

1319
template <typename IntT>

src/MathTest.cc

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <assert.h>
2+
#include <errno.h>
3+
#include <string.h>
4+
#include <sys/time.h>
5+
#include <sys/types.h>
6+
#include <unistd.h>
7+
8+
#include "Math.hh"
9+
#include "UnitTest.hh"
10+
11+
using namespace std;
12+
using namespace phosg;
13+
14+
int main(int, char**) {
15+
{
16+
fprintf(stderr, "-- gcd\n");
17+
expect_eq(30, gcd(30, 30));
18+
expect_eq(10, gcd(30, 80));
19+
expect_eq(1, gcd(30, 1));
20+
}
21+
22+
{
23+
fprintf(stderr, "-- reduce_fraction\n");
24+
expect_eq(make_pair(1, 2), reduce_fraction(4, 8));
25+
expect_eq(make_pair(1, 1), reduce_fraction(4, 4));
26+
expect_eq(make_pair(1, 1), reduce_fraction(1, 1));
27+
expect_eq(make_pair(15, 2), reduce_fraction(45, 6));
28+
}
29+
30+
return 0;
31+
}

0 commit comments

Comments
 (0)