Browse Source

karatsuba multiplication fonction added

remotes/origin/multiplication
fdai7930 11 months ago
parent
commit
cf0cbc304b
  1. 24
      src/multiplication.c
  2. 1
      src/multiplication.h

24
src/multiplication.c

@ -231,6 +231,30 @@ int bitwise_multiply(int num1, int num2) {
return result; 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;
}

1
src/multiplication.h

@ -31,6 +31,7 @@ int repeated_division_multiply(int num1, int num2);
int bernoulli_multiply(int num, int bernoulli); int bernoulli_multiply(int num, int bernoulli);
float power_multiply(float base, int exponent); float power_multiply(float base, int exponent);
int bitwise_multiply(int num1, int num2); int bitwise_multiply(int num1, int num2);
int karatsuba_multiply(int num1, int num2);

Loading…
Cancel
Save