|
|
@ -231,6 +231,30 @@ int bitwise_multiply(int num1, int num2) { |
|
|
|
return result; |
|
|
|
} |
|
|
|
|
|
|
|
int karatsuba_multiply(int num1, int num2) { |
|
|
|
// Base case: If numbers are less than 10, return their product directly |
|
|
|
if (num1 < 10 || num2 < 10) { |
|
|
|
return num1 * num2; |
|
|
|
} |
|
|
|
|
|
|
|
int m = (int)fmax(log10(num1), log10(num2)) + 1; // Maximum length of numbers |
|
|
|
int m2 = m / 2; // Divide maximum length by two |
|
|
|
|
|
|
|
// Divide numbers into parts |
|
|
|
int a = num1 / pow(10, m2); |
|
|
|
int b = num1 % (int)pow(10, m2); |
|
|
|
int c = num2 / pow(10, m2); |
|
|
|
int d = num2 % (int)pow(10, m2); |
|
|
|
|
|
|
|
// Calculate intermediate products |
|
|
|
int ac = karatsuba_multiply(a, c); |
|
|
|
int bd = karatsuba_multiply(b, d); |
|
|
|
int ad_bc = karatsuba_multiply(a + b, c + d) - ac - bd; |
|
|
|
|
|
|
|
// Calculate the final result |
|
|
|
return ac * (int)pow(10, 2 * m2) + ad_bc * (int)pow(10, m2) + bd; |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|