Your question has already been answered in the article that you referred to: "The main step of Karatsuba works for any base B and any m, but the recursive algorithm is most effective when m is n / 2, rounded up" .. n
, which is the number of digits , and 0 <= value_of_digit <B.
Some perspectives that may help:
You are allowed (and required!) To use elementary operations, such as number_of_digits // 2
and divmod(digit_x * digit_x, B)
... in school arithmetic, where B is 10, you need (for example) that divmod(9 * 8, 10)
creates (7, 2)
.
When implementing arithmetic of a large number on a computer, B is usually made with the greatest power of 2, which will support the operation of elementary multiplication. For example, in a CPython implementation on a 32-bit machine, B is selected equal to 2 ** 15 (i.e. 32768), because then product = digit_x * digit_y; hi = product >> 15; lo = product & 0x7FFF;
product = digit_x * digit_y; hi = product >> 15; lo = product & 0x7FFF;
works without overflow and without taking into account the sign bit.
I'm not sure what you are trying to achieve with a Python implementation that uses B == 2, with numbers represented by Python intuitions, whose C implementation already uses the Karatsuba algorithm to multiply numbers that are large enough to make it worthwhile. It cannot be speed.
As a training exercise, you can try to present the number as a list of numbers, with basic B being an input parameter.
source share