【问题标题】:How to do a larger number operations [duplicate]如何进行更大数量的操作[重复]
【发布时间】:2020-06-10 17:06:41
【问题描述】:

我需要计算比长整数可以存储的大得多的数字(例如 1234567890*1234)。 有没有办法超过那个内存容量?

【问题讨论】:

标签: java long-integer


【解决方案1】:

查看BigInteger。这是一个例子。

BigInteger v = BigInteger.valueOf(1234567890);
BigInteger prod = v.multiply(BigInteger.valueOf(1234));
System.out.println(prod);

如果数字不适合长,则为它们提供一个字符串。

v = new BigInteger("4994949234567890");
prod = v.multiply(new BigInteger("1234920292029292292"));
System.out.println(prod);

打印

1523456776260
6168364167424068724128019127703880

对应的浮点数是BigDecimal

【讨论】:

    【解决方案2】:

    您可以使用:

    BigInteger num= new BigInteger("1234567890*1234");
    

    【讨论】:

    • BigInteger 不会为其构造函数采用算术表达式,您需要 new BigInteger("1234567890").multiply(BigInteger.valueOf(1234))
    【解决方案3】:

    如果您想坚持使用纯 Java,可以使用 BigInteger,但也可以使用 jscience。这是一个很棒的库,针对这类问题进行了大量优化。

    也许LargeInteger 这门课对你有好处。

    Here 是你的一个例子:

    LargeInteger dividend = LargeInteger.valueOf("3133861182986538201");
    LargeInteger divisor = LargeInteger.valueOf("25147325102501733369");
    Rational rational = Rational.valueOf(dividend, divisor);
    System.out.println("rational  = " + rational);
    
    > rational  = 41/329
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      • 1970-01-01
      • 2019-06-26
      • 2014-01-06
      • 2014-05-18
      • 1970-01-01
      相关资源
      最近更新 更多