-
Notifications
You must be signed in to change notification settings - Fork 178
/
karatsuba_algorithm.cpp
67 lines (53 loc) · 1.29 KB
/
karatsuba_algorithm.cpp
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
/* Notes
- any algorithm for multiplying two numbers of n-digits, it takes 2n computation
steps
- any algorithm for adding two numbers of n-digits, it takes n computation steps
- Elementary school algorithm have complexity of - O(n^2)
x = a*10^n/2 + b
if a num = ab, n = number of digits
*/
#define ll long long
ll pow(ll a, ll b) {
ll res = 1;
for (int i = 0; i < b; i++)
res *= a;
return res;
}
// recursive function
ll karatsuba(ll x, ll y) {
if (x < 10 || y < 10)
return x * y;
ll temp = x;
int n, n_x = 0, n_y = 0;
while (temp) {
n_x++;
temp /= 10;
}
temp = y;
while (temp) {
n_y++;
temp /= 10;
}
n = std::max(n_x, n_y);
ll half = n / 2;
ll a = x / pow(10, half);
ll b = x % pow(10, half);
ll c = y / pow(10, half);
ll d = y % pow(10, half);
ll ac = karatsuba(a, b);
ll bd = karatsuba(b, d);
ll ad_plus_bc = karatsuba(a + b, c + d) - ac - bd;
return ac * pow(10, 2 * half) + (ad_plus_bc * pow(10, half)) + bd;
}
// testing the code
int main(void) {
ll a, b;
std::cout << "Enter num1: ";
std::cin >> a;
std::cout << "Enter num2: ";
std::cin >> b;
std::cout << "Normal Multiplication: " << a * b << std::endl;
std::cout << "Karatsuba's Multiplication: " << karatsuba(a, b) << std::endl;
return 0;
}