问题
Possible Duplicate:
diffucilty with BigInteger
import java.math.BigInteger;
public class KillerCode{
public static void main(String[]args){
BigInteger sum=null;
for(int i=1;i<=1000;i++){
sum=sum+Math.pow(i, i);
System.out.println(sum);
}
}
}
When I try to run this code the following error message is coming up.
The operator + is undefined for the argument type(s) BigInteger,double.
How can I solve this? Thank you.
回答1:
You cannot use the typical math operators with BigIntegers, check here http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html
you need to use BigInteger.add(your numbers here)
Further Explination,
sum = sum.add(new BigInteger(i).pow(i));
回答2:
You cannot do it because sum is not an integer, but a reference to an object.
Unlike C++, java doesn't allow operator overloading, so you need to use the class methods to perform operations.
回答3:
Initialize
sum
to a meaningful, NON-null
, value (you current initialize tonull
):BigInteger sum = BigInteger.ZERO;
else the expression
sum = sum.add(...)
won't be meaningful (unless you want a
NullPointerException
).Use the static factory
BigInteger.valueOf(long)
to map an integer value to aBigInteger
.Don't use the expression
new BigInteger(i)
. The constructor invoked bynew BigInteger(i)
isBigInteger(byte[])
, with erroneous results (for your purposes) for values larger than 255 (which you have...).Use
BigInteger.add(BigInteger)
for addition.Use
BigInteger.pow(int)
instead ofMath.pow(int,int)
; since you're doing (Big) integer arithmetic, avoid anything that maps your work into the floating point world, i.edouble
orfloat
, or you'll have lost the advantages of theBigInteger
.
回答4:
BigInteger doesn't have a +
operator defined. According to its javadocs found here, you can use the .add() function to achieve the result you're seeking.
来源:https://stackoverflow.com/questions/12888848/java-biginteger