I’m writing a program (in C) in which I try to calculate powers of big numbers in an as short of a period as possible. The numbers I represent as vectors of digits, so all operations have to be written by hand.
The program would be much faster without all the allocations and deallocations of intermediary results. Is there any algorithm for doing integer multiplication, in-place? For example, the function
void BigInt_Times(BigInt *a, const BigInt *b);
would place the result of the multiplication of a and b inside of a, without using an intermediary value.
Here,
muln()is 2n (really, n) by n = 2n in-place multiplication for unsigned integers. You can adjust it to operate with 32-bit or 64-bit “digits” instead of 8-bit. The modulo operator is left in for clarity.muln2()is n by n = n in-place multiplication (as hinted here), also operating on 8-bit “digits”.Output:
I think this is the best we can do in-place. One thing I don’t like about
muln2()is that it has to accumulate bigger intermediate products and then propagate a bigger carry.