I learnt about Karatsuba algorithm which allows me to multiply very big numbers using divide and conquer method.
Here's my code. I wrote a function which returns the length of a number then I write the multiply function and I used the method with 4 recursive calls.
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
int numberLength(long long value) {
int counter = 0;
while (value != 0)
{
counter++;
value /= 10;
}
return counter;
}
long long multiply(long x, long y) {
int xLength = numberLength(x);
int yLength = numberLength(y);
int n = max(xLength, yLength);
if (n < 10) {
return x*y;
}
long multiplier = pow(10, n/2);
long xS = x/multiplier;
long xD = x - (xS * multiplier);
long yS = y/multiplier;
long yD = y - (yS * multiplier);
return multiply(xS,yS*pow(10,n)) + multiply(xS,yD*pow(10,n/2)) + multiply(xD,yS*pow(10,n/2)) + multiply(xD,yD);
}
The problem is that if I call the function multiply() with some numbers length bigger than 10 then I get the error Segmentation fault. Where's the problem?
You are going to breach the stack limit and that would lead to a stack overflow in the recursive
multiply()
function for numbers with lengths >= 10. I tried this driver functionand compiled this with
-fsanitize=address
. This was the output:Also, try compiling your program with
-fsanitize=undefined
to take a look at other errors in the logic, one beingPassing in
multiply(123456789, 1234567891)
will cause an overflow since that value can't be accommodated in along
(usually of 32-bits). Change that to: