-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOperations.cpp
More file actions
44 lines (37 loc) · 878 Bytes
/
Copy pathOperations.cpp
File metadata and controls
44 lines (37 loc) · 878 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
/*
* Implementations of Arithmetic Operations in Mathmetics.
*/
// Al Khwarizmi - Multiplication in France -- O(n2)
#include <iostream>
#include <utility>
using namespace std;
int multiply(int x, int y) {
if (y == 0) return 0;
if (y % 2 == 0)
return multiply(x, y / 2) * 2;
else
return multiply(x, y / 2) * 2 + x;
}
// Division x = y * q + r
pair<int, int> division(int x, int y) {
if (x == 0) return make_pair(0, 0);
int q, r;
pair<int, int> Qr = make_pair(q, r);
Qr = division(x / 2, y);
q = Qr.first; r = Qr.second;
q *= 2; r *= 2;
if (x % 2 != 0) {
r ++;
}
if (r >= y) {
r -= y;
q ++;
}
return make_pair(q, r);
}
int main(void)
{
cout << multiply(2, 5) << endl;
cout << division(30, 4).first << " " << division(30, 4).second << endl;
return 0;
}