Optimize BigInteger.Multiply
by Toom-Cook multiplication
#112876
+864
−220
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
https://en.wikipedia.org/wiki/Toom%E2%80%93Cook_multiplication
I updated
BigInteger
multiplication to use the Toom-3 algorithm.The current Karatsuba algorithm has a time complexity of$O(n^{\log_2{3}}) \simeq O(n^{1.58})$ , which is expected to improve to $O(n^{\log_3{5}}) \simeq O(n^{1.46})$ resulting in better performance.
in other languages:
About the Implementation
SquareThreshold
andMultiplyKaratsubaThreshold
.{[MethodImpl(MethodImplOptions.AggressiveInlining)]
to avoid stack consumption when determining the algorithm.Why
MultiplyToom3Threshold
is 256?Based on the benchmark results, I decided to set
MultiplyToom3Threshold
to 256.Benchmark
When the number of digits is small, the preprocessing for algorithm selection is relatively high, leading to a slight regression—for example, a computation that previously took 19 μs now takes 20 μs.
However, as the number of digits increases, performance improves; for instance, a multiplication that used to take 750 μs is now completed in 690 μs.
Code