-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCTCI-8.5.cpp
More file actions
37 lines (35 loc) · 954 Bytes
/
CTCI-8.5.cpp
File metadata and controls
37 lines (35 loc) · 954 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
// Recursive multiply
#include <bits/stdc++.h>
using namespace std;
int recursiveMultiply(int a, int b) {
// cout << a << ":" << (a&1) << "x" << b << ":" << (b&1) <<"\n";
if(a == 1) {
return b;
}
if(b == 1) {
return a;
}
if((a&1) == 0) {
// Last bit 0 - divide by 2
return recursiveMultiply(a >> 1, b) << 1;
}
if((b&1) == 0) {
// Last bit 0 - divide by 2
return recursiveMultiply(a, b >> 1) << 1;
}
return b + (recursiveMultiply(a >> 1, b) << 1); // b + (b*(a-1)/2)*2
}
int main() {
int num1 = 0, num2 = 0;
// Due to time constraints, this program does not validate non-integer inputs.
while(num1 <= 0) {
cout << "First Positive Integer: ";
cin >> num1;
}
while(num2 <= 0) {
cout << "Second Positive Integer: ";
cin >> num2;
}
cout << "Product: " << recursiveMultiply(num1, num2) << "\n";
return 0;
}