diff --git a/src/multiplication.c b/src/multiplication.c index 062c50b..1832133 100644 --- a/src/multiplication.c +++ b/src/multiplication.c @@ -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; +} + diff --git a/src/multiplication.h b/src/multiplication.h index 342bd91..8653b4a 100644 --- a/src/multiplication.h +++ b/src/multiplication.h @@ -31,6 +31,7 @@ int repeated_division_multiply(int num1, int num2); int bernoulli_multiply(int num, int bernoulli); float power_multiply(float base, int exponent); int bitwise_multiply(int num1, int num2); +int karatsuba_multiply(int num1, int num2);