java.bigInteger valueOf 如何工作?

发布于 2024-08-18 02:57:53 字数 618 浏览 1 评论 0原文

我正在制作一个涉及大数字的项目,没有 BigInteger、BigDecimal 等。我已经成功完成了所有基础知识,但现在我需要添加计算阶乘的能力。我的 BigNumber 将数据存储为 int[] 。

这是一个使用 BigInteger 的示例解决方案,但如果没有我的号码的实际值,我就无法使用它。

    BigInteger n = BigInteger.ONE;
    for (int i=1; i<=20; i++) {
        n = n.multiply(BigInteger.valueOf(i));
        System.out.println(i + "! = " + n);
    }

那么如何计算价值呢?将整数从最后到第一个相加,将十乘以 10,将百乘以 100,依此类推,并将其存储为 long ?

大整数的来源: http://developer.classpath.org/doc/java/math/ BigInteger-source.html

I'm making a project concerned big numbers without BigInteger, BigDecimal etc. I've managed to do all the basics but now I need to add ability to count factorials. My BigNumber stores data as int[] .

Here's a sample solution with BigInteger but I can't use it without having the actual value of my number.

    BigInteger n = BigInteger.ONE;
    for (int i=1; i<=20; i++) {
        n = n.multiply(BigInteger.valueOf(i));
        System.out.println(i + "! = " + n);
    }

So how to count the value ? Add ints from last to first, multiplying tens by 10, hundreds by 100 and so on and so on and store it as long ?

Source of BigInteger :
http://developer.classpath.org/doc/java/math/BigInteger-source.html

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

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

发布评论

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

评论(1

狼亦尘 2024-08-25 02:57:53

那么如何计算这个值呢?将整数从最后到第一个相加,将十乘以 10、将百乘以 100 等等,并将其存储为 long ?

我不认为将其存储为 long 是您想要的。如果该值大于 Long.MAX_VALUE 会发生什么?

如果 nBigInteger,则 n.multiply(BigInteger.valueOf(i)); 应返回 BigInteger > 对象。 multiply 方法应该知道如何对两个 BigInteger 对象进行乘法运算,而不需要将它们转换为 long。一种方法是使用我们在小学学到的乘法进位算法循环遍历每个数字。如果您的值是天文数字,这将非常慢,但它确实具有易于理解和实现的好处。

So how to count the value ? Add ints from last to first, multiplying tens by 10, hundreds by 100 and so on and so on and store it as long ?

I don't think storing it as a long is what you intend. What would happen if the value gets bigger than Long.MAX_VALUE?

If n is a BigInteger, then n.multiply(BigInteger.valueOf(i)); should return a BigInteger object. The multiply method should know how to do multiplication with two BigInteger objects without needing to convert them to long. One way of doing that is to loop through each digit using the multiply-and-carry algorithm that we learned in grade school. This will be pretty slow if your values are astronomical, but it does have the benefit of being easy to understand and implement.

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