What is the most efficient way to compute the product
a1 b2 c3 d4 e5 ...
assuming that squaring costs about half as much as multiplication? The number of operands is less than 100.
Is there a simple algorithm also for the case that the multiplication time is proportional to the square of operand length (as with java.math.BigInteger
)?
The first (and only) answer is perfect w.r.t. the number of operations.
Funnily enough, when applied to sizable BigInteger
s, this part doesn't matter at all. Even computing abbcccddddeeeee without any optimizations takes about the same time.
Most of the time gets spent in the final multiplication (BigInteger
implements none of the smarter algorithms like Karatsuba, Toom–Cook, or FFT, so the time is quadratic). What's important is assuring that the intermediate multiplicands are about the same size, i.e., given numbers p, q, r, s of about the same size, computing (pq) (rs) is usually faster than ((pq) r) s. The speed ratio seems to be about 1:2 for some dozens of operands.
Update
In Java 8, there are both Karatsuba and Toom–Cook multiplications in BigInteger
.
O(N log(N)^2)
algorithm to do this (where N is the size of the final number). But you'll need to go beyondjava.math.BigInteger
to achieve it. – DimBigInteger
s, but currently I don't know how big. – SupinatorBigInteger implements none of the smarter algorithms like Karatsuba, Toom–Cook, or FFT, so the time is quadratic
what implementation ofjava.math.BigInteger
does this refer/apply to? – Capsize