Java BigInteger [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-12-10 18:53:42

问题


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:


  1. Initialize sum to a meaningful, NON-null, value (you current initialize to null):

    BigInteger sum = BigInteger.ZERO;
    

    else the expression

    sum = sum.add(...)
    

    won't be meaningful (unless you want a NullPointerException).

  2. Use the static factory BigInteger.valueOf(long) to map an integer value to a BigInteger.

    Don't use the expression new BigInteger(i). The constructor invoked by new BigInteger(i) is BigInteger(byte[]), with erroneous results (for your purposes) for values larger than 255 (which you have...).

  3. Use BigInteger.add(BigInteger) for addition.

  4. Use BigInteger.pow(int) instead of Math.pow(int,int); since you're doing (Big) integer arithmetic, avoid anything that maps your work into the floating point world, i.e double or float, or you'll have lost the advantages of the BigInteger.




回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!