Skip to content

Commit 4ada9dd

Browse files
committed
Added recursive_multiply.cpp; Problem no 8.5
1 parent 4e5b2ff commit 4ada9dd

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

recursive_multiply.cpp

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include <iostream>
2+
3+
// Solution no 1
4+
static std::size_t multiply1(std::size_t n1, std::size_t n2)
5+
{
6+
if(n2 == 1)
7+
return n1;
8+
return multiply1(n1, n2 - 1) + n1;
9+
}
10+
11+
// Solution no 2
12+
static std::size_t multiply2(std::size_t n1, std::size_t n2)
13+
{
14+
if(n2 == 1)
15+
return n1;
16+
auto halfn2 = n2 >> 1;
17+
return (multiply2(n1, halfn2) << 1) + ((n2 & 1) ? n1 : 0);
18+
}
19+
20+
struct Solution1
21+
{
22+
std::size_t operator()(std::size_t n1, std::size_t n2)
23+
{
24+
return multiply1(n1, n2);
25+
}
26+
};
27+
28+
struct Solution2
29+
{
30+
std::size_t operator()(std::size_t n1, std::size_t n2)
31+
{
32+
return multiply2(n1, n2);
33+
}
34+
};
35+
36+
template<typename Sol>
37+
static void runMultiply(std::size_t n1, std::size_t n2)
38+
{
39+
std::cout << "Input: n1 = " << n1 << ", n2 = " << n2 << "\n";
40+
std::size_t result = Sol { } (n1, n2);
41+
std::cout << "Output: " << result << "\n";
42+
}
43+
44+
static void run(std::size_t n1, std::size_t n2)
45+
{
46+
static std::size_t runCount = 0;
47+
std::cout << "--------RUN: " << runCount << " --------\n";
48+
++runCount;
49+
std::cout << "**Solution no 1**\n";
50+
runMultiply<Solution1>(n1, n2);
51+
std::cout << "**Solution no 2**\n";
52+
runMultiply<Solution2>(n1, n2);
53+
}
54+
55+
int main()
56+
{
57+
run(10, 30);
58+
run(20, 23);
59+
run(12, 11);
60+
run(1, 1);
61+
run(2, 3);
62+
run(4, 4);
63+
run(8, 4);
64+
run(3, 5);
65+
return 0;
66+
}

0 commit comments

Comments
 (0)