预测乘法的位数

发布于 2024-11-18 07:47:07 字数 69 浏览 4 评论 0 原文

我需要找到非常大的乘法的位数(每个乘法大约 300 位)。我想知道是否有一个技巧可以在不实际执行计算的情况下预测乘积的位数。

I need to find the number of digits of very large multiplications (about 300 digits each). I was wondering if there is a trick to predict the number of digits that the product will be without actually performing the calculation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

春庭雪 2024-11-25 07:47:07

可以通过精确计算位数/Math.html#log10%28double%29" rel="nofollow noreferrer">两个被乘数以 10 为底的对数加 1,如下所示:

public static void main(String[] args) {
    DecimalFormat f = new DecimalFormat("#");
    double num1 = 12345678901234567890d;
    double num2 = 314159265358979d;

    // Here's the line that does the work:
    int numberOfDigits = (int) (Math.log10(num1) + Math.log10(num2)) + 1;

    System.out.println(f.format(num1) + " * " + f.format(num2) + " = " + 
        f.format((num1 * num2)) + ", which has " + numberOfDigits + " digits");
}

输出:

12345678901234567000 * 314159265358979 = 3878509413969699000000000000000000, which has 34 digits

这适用于任意大的数字。

The number of digits can be calculated exactly by the rounded (down) sum of the base 10 log of the two multiplicands plus 1, as follows:

public static void main(String[] args) {
    DecimalFormat f = new DecimalFormat("#");
    double num1 = 12345678901234567890d;
    double num2 = 314159265358979d;

    // Here's the line that does the work:
    int numberOfDigits = (int) (Math.log10(num1) + Math.log10(num2)) + 1;

    System.out.println(f.format(num1) + " * " + f.format(num2) + " = " + 
        f.format((num1 * num2)) + ", which has " + numberOfDigits + " digits");
}

Output:

12345678901234567000 * 314159265358979 = 3878509413969699000000000000000000, which has 34 digits

This will work for arbitrarily large numbers.

影子的影子 2024-11-25 07:47:07

Cristobalito 的回答几乎明白了。让我把“关于”说得更精确一些:

假设第一个数字有 n 位,第二个数字有 m 位。它们的最低值分别是 10^(n-1) 和 10^(m-1)。该乘积将是所能达到的最低值,即 10^(m+n-2),即 m+n-1 位数字。

它们的最高值分别是 10^n - 1 和 10^m - 1。该乘积将是最高的,并且为 10^(n+m) - 10^n - 10^m + 1,最多有 m+n 位。

因此,如果将 n 位数字乘以 m 位数字,则乘积将具有 m+n-1 或 m+n 位。

类似的逻辑也适用于其他基数,例如基数 2。

Cristobalito's answer pretty much gets it. Let me make the "about" more precise:

Suppose the first number has n digits, and the second has m. The lowest they could be is 10^(n-1) and 10^(m-1) respectively. That product would the lowest it could be, and would be 10^(m+n-2), which is m+n-1 digits.

The highest they could be is 10^n - 1 and 10^m - 1 respectively. That product would be the highest it could be, and would be 10^(n+m) - 10^n - 10^m + 1, which has at most m+n digits.

Thus if you are multiplying an n-digit number by an m-digit number, the product will have either m+n-1 or m+n digits.

Similar logic holds for other bases, such as base 2.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文