如何使用BigInteger? [英] How to use BigInteger?

查看:112
本文介绍了如何使用BigInteger?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,但是无效:

I have this piece of code, which is not working:

BigInteger sum = BigInteger.valueOf(0);
for(int i = 2; i < 5000; i++) {
    if (isPrim(i)) {
        sum.add(BigInteger.valueOf(i));
    }
}

sum变量始终为0.我在做什么错误?

The sum variable is always 0. What am I doing wrong?

推荐答案

BigInteger 是不可变的。 javadocs声明 add() [r] eturns一个BigInteger,其值为(this + val)。因此,您无法更改 sum ,您需要将 add 方法的结果重新分配给 sum 变量。

BigInteger is immutable. The javadocs states that add() "[r]eturns a BigInteger whose value is (this + val)." Therefore, you can't change sum, you need to reassign the result of the add method to sum variable.

sum = sum.add(BigInteger.valueOf(i));

这篇关于如何使用BigInteger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆