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?