Karatsuba Integer Multiplication Algorithm
Karatsuba Integer Multiplication Algorithm
#include <bits/stdc++.h>
using namespace std;
return ans;
}
int n = adjust_len(x,y);
if(n == 0){
return 0;
}
if(n == 1){
return (x[0] - '0')*(y[0] - '0');
}
string xl,xr,yl,yr;
long long lh = n/2;
long long rh = n - lh;
xl = x.substr(0,lh);
xr = x.substr(lh,rh);
yl = y.substr(0,lh);
yr = y.substr(lh,rh);
string a1 = addBin(xl,xr);
string a2 = addBin(yl,yr);
long long s3 = multiply_bin(a1,a2);
long long s4 = s3 - s2 - s1;
long long s5 = s1 * (1LL << (2 * (n - n/2))) + s4 * (1LL <<
(n - n/2)) + s2;
return s5;
}
int main()
{
string x,y;
cout << "Enter the binary numbers to multiply : ";
cin >> x >> y;
long long result = multiply_bin(x,y);
cout << "Multiplication is : " << result << endl;
return 0;
}
Output :
Time-Complexity:
● Recursive Splitting(Divide part): The
multiply_bin function divides the binary strings
into two halves.
○ For a binary string of length n, each level
performs 3 recursive calls to multiply_bin
function.
○ So, we are dividing a problem of length n
into 3 problems of length (n/2).
● addBin function: takes O(n) time to add two
binary strings of length n.
● The combination of results require few additions
and shifts, thus it is linear in nature
○ So, the conquer part takes O(n) time.
● Recurrence Relation :
○ T(n) = 3T(n/2) + n
● Solving the above equation the time
complexity comes out to be approx. O(n^1.58).
Space Complexity:
● Recursive stack space: depends upon the
length of the strings. For length n string it
takes O(log n) space.
● Each level needs space proportional to the
size of the numbers being handled, which is
O(n)
● Overall Space Complexity: O(n)