-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrecursive_multiply.cpp
More file actions
49 lines (44 loc) · 978 Bytes
/
recursive_multiply.cpp
File metadata and controls
49 lines (44 loc) · 978 Bytes
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
/* Write a recursive function to multiply two positive integers without using the * operator
(or / operator). You can use addition, subtraction and bit shifting, but you should minimize
the number of those operations. */
#include <algorithm>
#include <iostream>
int recursiveMultiplication(int n, int op2, int acc)
{
if ((op2 & 1) != 0)
{
if (acc == 0)
{
acc = n;
}
else
{
acc += n;
}
}
op2 = op2 >> 1;
if (op2 == 0)
return acc;
n += n;
return recursiveMultiplication(n, op2, acc);
}
int recursiveMultiplication(int op1, int op2)
{
if (op1 < op2)
{
std::swap(op1, op2);
}
return recursiveMultiplication(op1, op2, 0);
}
void test(int op1, int op2)
{
std::cout << op1 << " * " << op2 << " = " << recursiveMultiplication(op1, op2) << std::endl;
}
int main()
{
test(8, 1);
test(3, 8);
test(8, 5);
test(8, 8);
return 0;
}