Skip to content

Commit 0ffc6eb

Browse files
committed
EPI: primitive multiply (CPP)
1 parent 1f2fc42 commit 0ffc6eb

File tree

3 files changed

+58
-4
lines changed

3 files changed

+58
-4
lines changed
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
cpp/cpp_build/**
1+
cpp/cpp_build/**
2+
Scratchpad.ipynb

elements-of-programming-interviews/cpp/primitive_multiply.cc

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,60 @@
11
#include "test_framework/generic_test.h"
2+
3+
void printBin(unsigned long long val, size_t len, const std::string& suffix) {
4+
std::string binval;
5+
for (size_t i = 0; i < len; i++) {
6+
binval.append(val & 1 ? "1" : "0");
7+
val >>= 1;
8+
}
9+
reverse(binval.begin(), binval.end());
10+
printf("%s (%s)\n", binval.c_str(), suffix.c_str());
11+
}
12+
13+
unsigned long long Add(unsigned long long a, unsigned long long b) {
14+
/*
15+
total = a^b
16+
carry = (a & b) << 1
17+
while carry:
18+
newTotal = total ^ carry
19+
newCarry = (total & carry) << 1
20+
total, carry = newTotal, newCarry
21+
return total
22+
*/
23+
unsigned long long total = a ^ b;
24+
unsigned long long carry = (a & b) << 1;
25+
while (carry) {
26+
unsigned long long newTotal = total ^ carry;
27+
carry = (total & carry) << 1;
28+
total = newTotal;
29+
}
30+
return total;
31+
}
32+
233
unsigned long long Multiply(unsigned long long x, unsigned long long y) {
3-
// TODO - you fill in here.
4-
return 0;
34+
/*
35+
- Can only use assignment, comparisons, and bitwise operations (&, |, ~, ^)
36+
- Lshift is a multiply by 2
37+
- Clearing the lowest bit and setting all to the right of it: subtract 1
38+
- Adding: bitwise xor with carry
39+
(3+3=6)
40+
11 +
41+
11 =
42+
110
43+
- Multiply can be iterative addition, but without subtraction this will be
44+
hard
45+
- Multiply: prod = 0. Until b=0, if lowest bit is set, add prod+=a. Right
46+
shift b, leftshift a. (3*3=9) 11 * 11 = 1001 (5*5=25) 101 * 101 = 11001
47+
*/
48+
unsigned long long prod = 0;
49+
while (y) {
50+
if (y & 1) {
51+
prod = Add(x, prod);
52+
}
53+
y >>= 1;
54+
x <<= 1;
55+
}
56+
57+
return prod;
558
}
659

760
int main(int argc, char* argv[]) {

elements-of-programming-interviews/problem_mapping.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ problem_mapping = {
7272
},
7373
"4.05 Compute product without arithmetical operators": {
7474
"C++: primitive_multiply.cc": {
75-
"passed": 0,
75+
"passed": 10006,
7676
"total": 10006
7777
},
7878
"Java: PrimitiveMultiply.java": {

0 commit comments

Comments
 (0)