-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
58 lines (48 loc) · 1.12 KB
/
main.cpp
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
// Created by Marco Bonino on 22/10/2021.
#include <gtest/gtest.h>
int power(int base, int exp)
{
int result = 1;
for (; exp > 0; --exp)
result = result * base;
return result;
}
int powerFastImpl(int base, int exp)
{
if (exp == 0)
return 1;
else if (exp == 1)
return base;
bool exp_odd = (exp % 2) == 1;
int exp_half = exp / 2;
int tmp = powerFastImpl(base, exp_half);
int result = tmp * tmp;
if (exp_odd)
result = result * base;
return result;
}
TEST(Power, linearImpl)
{
ASSERT_EQ(power(3, 3), 27);
ASSERT_EQ(power(2, 4), 16);
ASSERT_EQ(power(2, 6), 64);
ASSERT_EQ(power(20, 2), 400);
ASSERT_EQ(power(20, 0), 1);
}
TEST(Power, lognImpl)
{
ASSERT_EQ(powerFastImpl(3, 3), 27);
ASSERT_EQ(powerFastImpl(2, 4), 16);
ASSERT_EQ(powerFastImpl(2, 6), 64);
ASSERT_EQ(powerFastImpl(20, 2), 400);
ASSERT_EQ(powerFastImpl(20, 0), 1);
}
TEST(Power, cmpImpl)
{
ASSERT_EQ(power(2, 30), powerFastImpl(2, 30));
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}