简体   繁体   English

Java 使用哪种算法进行乘法运算?

[英]Which algorithm does Java use for multiplication?

The list of possible algorithms for multiplication is quite long:可能的乘法算法列表很长:

  • Schoolbook long multiplication教科书长乘法
  • Karatsuba algorithm唐叶算法
  • 3-way Toom–Cook multiplication 3 路 Tom-Cook 乘法
  • k-way Toom–Cook multiplication k-way Tom-Cook 乘法
  • Mixed-level Toom–Cook混合级别的 Toom–Cook
  • Schönhage–Strassen algorithm Schönhage–Strassen 算法
  • Fürer's algorithm Fürer 算法

Which one is used by Java by default and why? Java默认使用哪一个,为什么? When does it switch to a "better performance" algorithm?它什么时候切换到“更好的性能”算法?

Well... the * operator will use whatever the hardware provides.好吧... *运算符将使用硬件提供的任何内容。 Java has no say in it. Java 没有发言权。

But if you are talking about BigInteger.multiply(BigInteger) , the answer depends on the Java version.但是如果你在谈论BigInteger.multiply(BigInteger) ,答案取决于 Java 版本。 For Java 11 it uses:对于 Java 11,它使用:

  • naive "long multiplication" for small numbers,小数的天真“长乘法”,
  • Karatsuba algorithm for medium sized number, and中型数的 Karatsuba 算法,以及
  • 3-way Toom–Cook multiplication for large numbers.大数的 3 路 Toom-Cook 乘法。

The thresholds are Karatsuba for numbers represented by 80 to 239 int values, an 3-way Toom-Cook for >= 240 int values.阈值是由 80 到 239 int值表示的数字的 Karatsuba,对于 >= 240 int值的 3-way Toom-Cook。 The smaller of the numbers being multiplied controls the algorithm selection.乘以较小的数字控制算法选择。


Which one is used by Java by default and why? Java默认使用哪一个,为什么?

Which ones?哪个? See above.看上面。

Why?为什么? Comments in the code imply that the thresholds were chosen empirically;代码中的注释暗示阈值是根据经验选择的; ie someone did some systematic testing to determine which threshold values gave the best performance 1 .即有人做了一些系统的测试,以确定哪些阈值给出了最好的性能1

You can find more details by reading the source code 2 .您可以通过阅读源代码2找到更多详细信息。


1 - The current implementation BigInteger implementation hasn't changed significantly since 2013, so it is possible that it doesn't incorporate more recent research results. 1 - 当前的实现BigInteger实现自 2013 年以来没有显着变化,因此它可能没有包含更多最近的研究结果。
2 - Note that this link is to the latest version on Github. 2 - 请注意,此链接指向 Github 上的最新版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM