Skip to content

Commit bcc8e20

Browse files
author
Bhrigu Kansra
authored
Merge pull request #14 from joybanerjee08/master
Karatsuba in C++
2 parents 1e2bc40 + 954398b commit bcc8e20

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

multiplication/karatsuba.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#include <iostream>
2+
#include<string>
3+
#include <algorithm>
4+
#include <cmath>
5+
using namespace std;
6+
7+
int karatsuba(int x, int y){
8+
if ((to_string(x).length()==1) || (to_string(y).length()==1)) {
9+
return x*y;
10+
}
11+
else{
12+
int n = max(to_string(x).length(),to_string(y).length());
13+
int z = n / 2;
14+
int a = x / (int)pow(10,z);
15+
int b = x % (int)pow(10,z);
16+
int c = y / (int)pow(10,z);
17+
int d = y % (int)pow(10,z);
18+
int ac = karatsuba(a,c);
19+
int bd = karatsuba(b,d);
20+
int adbc = karatsuba(a+b,c+d) - ac - bd;
21+
return ac * pow(10,2*z) + (adbc * pow(10,z)) + bd;
22+
}
23+
}
24+
25+
int main() {
26+
cout << karatsuba (923,1723);
27+
}

0 commit comments

Comments
 (0)