Skip to content

Commit 001f01c

Browse files
committed
EPI: Primitive divide (py, cpp)
1 parent 0ffc6eb commit 001f01c

File tree

3 files changed

+50
-8
lines changed

3 files changed

+50
-8
lines changed
Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,41 @@
11
#include "test_framework/generic_test.h"
2-
int Divide(int x, int y) {
3-
// TODO - you fill in here.
4-
return 0;
2+
int Divide(int a, int b) {
3+
/*
4+
Divide x by y, using only subtraction, addition, and shifting.
5+
6+
Brute force would be to iteratively subtract until a remainder occurs, but
7+
this could take up to 2^n (e.g. (2^31 - 1) / 1).
8+
9+
Could we use the same strategy for multiply, but with subtraction?
10+
*/
11+
if (a < b || b == 0) {
12+
return 0;
13+
}
14+
15+
long long x = a;
16+
long long y = b;
17+
long long amount = 1;
18+
long long quotient = 0;
19+
while (x > y) {
20+
y <<= 1;
21+
amount <<= 1;
22+
}
23+
while (x) {
24+
if (x >= y) {
25+
x -= y;
26+
quotient += amount;
27+
} else {
28+
y >>= 1;
29+
amount >>= 1;
30+
}
31+
}
32+
return quotient;
533
}
634

735
int main(int argc, char* argv[]) {
836
std::vector<std::string> args{argv + 1, argv + argc};
937
std::vector<std::string> param_names{"x", "y"};
1038
return GenericTestMain(args, "primitive_divide.cc", "primitive_divide.tsv",
1139
&Divide, DefaultComparator{}, param_names);
40+
// Divide(2097428739, 186);
1241
}

elements-of-programming-interviews/problem_mapping.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,15 +86,15 @@ problem_mapping = {
8686
},
8787
"4.06 Compute quotient without arithmetical operators": {
8888
"C++: primitive_divide.cc": {
89-
"passed": 0,
89+
"passed": 10000,
9090
"total": 10000
9191
},
9292
"Java: PrimitiveDivide.java": {
9393
"passed": 0,
9494
"total": 10000
9595
},
9696
"Python: primitive_divide.py": {
97-
"passed": 0,
97+
"passed": 10000,
9898
"total": 10000
9999
}
100100
},

elements-of-programming-interviews/python/primitive_divide.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,22 @@
11
from test_framework import generic_test
22

33

4-
def divide(x: int, y: int) -> int:
5-
# TODO - you fill in here.
6-
return 0
4+
def divide(x, y):
5+
if (x < y or y == 0):
6+
return 0
7+
amount = 1
8+
quotient = 0
9+
while x > y:
10+
y <<= 1
11+
amount <<= 1
12+
while x:
13+
if x >= y:
14+
x -= y
15+
quotient += amount
16+
else:
17+
y >>= 1
18+
amount >>= 1
19+
return quotient
720

821

922
if __name__ == '__main__':

0 commit comments

Comments
 (0)