IT216 : ASSIGNMENT-5
Student I’d : 202301205
Code : Integer Multiplication (Karatsuba
Algorithm)
#include <bits/stdc++.h>
using namespace std;
int adjust_len(string &x, string &y)
{
int l1 = x.size();
int l2 = y.size();
if (l1 < l2)
{
for (int i = 0 ; i < l2 - l1 ; i++)
x = '0' + x;
return l2;
}
else if (l1 > l2)
{
for (int i = 0 ; i < l1 - l2 ; i++)
y = '0' + y;
}
return l1;
}
string addBin(string x,string y){
string ans = "";
int carry = 0;
int len = adjust_len(x,y);
for (int i = len-1 ; i >= 0 ; i--)
{
int Bit1 = x[i] - '0';
int Bit2 = y[i] - '0';
int sum = (Bit1 ^ Bit2 ^ carry)+'0';
ans = (char)sum + ans;
carry = (Bit1&Bit2) | (Bit2&carry) | (Bit1&carry);
}
if (carry) {
ans = '1' + ans;
}
return ans;
}
long int multiply_bin(string x, string y){
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);
long long s1 = multiply_bin(xl,yl);
long long s2 = multiply_bin(xr,yr);
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)