Error assigning to an an element in an array of Bi

2019-02-28 17:23发布

问题:

This is my code. It shows an error when I create an array of BigInteger and try to assign a value.

package test;
import java.math.*;
import java.lang.*;
import java.util.*;

public class Test {


    public static void main(String[] args) {

        BigInteger[] coef =  new BigInteger[78];
        int a=24;
        coef[a]=676557656534345345654645654654645645645645665656567; // Error comes here why
        System.out.println(coef[a]);
    }
}

回答1:

KEEP IN MIND ALWAYS

All numbers greater then 2147483647 will not be allowed as input because int range is -2147483648 to 2147483647 (Never forget it). If just in case your output is greater than the limit it will reverse and to its lowest value i.e -2147483648.

I recommend that you use:

coef[a]=new BigInteger("324576565343453456546456546546456456456455643671"); 

All important functions are in java.lang.Math class and you can perform arithmetic operations by passing a string to it.



回答2:

Java have static types and the auto boxing is only enabled for the wrappers of primitive types, like int to Integer, but not for BigInteger. You will have to do

new BigInteger("676557656534345345654645654654645645645645665656567") 

explicitly.



回答3:

First of all number grater then 2147483647 will not be allowed as input because int range is -2147483648 : 2147483647. if your your output is grater than this number it will automatically reverse and to its lowest value i.e -2147483648.

For bit number to operate with BigInteger take the number as String.

And as your problem I would suggest to use

coef[a]=new BigInteger("676557656534345345654645654654645645645645665656567"); 

As it gives you all relevant methods from java.lang.Math you can perform arithmetic operation by passing string in it..check this document

I have made Fabonacci series which give a huge output when a big number is passed to it....

Have a look at Fabonacci series on my GitHub

Hope it helps you!!



回答4:

    public static void main(String[] args) {
        BigInteger[] coef = new BigInteger[78];
        int a = 24;
        coef[a] = new BigInteger("676557656534345345654645654654645645645645665656567");
        System.out.println(coef[a]);
    }