将整个程序从Int转换为BigInteger

时间:2021-06-30 16:48:14

So I already have this whole entire class done in Int and now I had to convert it to BigInteger. Main objective is so I can store the coefficients as the BigIntegers for large coefficients. I am getting a null pointer error with the code but I knew that BigInteger was immutable and needed that format. Just maybe another eye or maybe I'm just not doing this correctly.

所以我已经在Int中完成了整个课程,现在我必须将它转换为BigInteger。主要目标是我可以将系数存储为大系数的BigIntegers。我得到代码的空指针错误,但我知道BigInteger是不可变的,需要这种格式。可能只是另一只眼睛或者我可能只是没有正确地做到这一点。

public class Polynomial {

private BigInteger[] coef;  // coefficients

private int deg;     // degree of polynomial (0 for the zero polynomial)



    /** Creates the constant polynomial P(x) = 1.
      */
    public Polynomial(){
        coef = new BigInteger[1];
        coef[0] = BigInteger.valueOf(1);
        deg = 0;
    }



    /** Creates the linear polynomial of the form P(x) =  x + a.
      */
    public Polynomial(int a){
        coef = new BigInteger[2];
        coef[1] = BigInteger.valueOf(1);
        coef[0] = BigInteger.valueOf(a);
        deg = 1;
    }




    /** Creates the polynomial P(x) = a * x^b.
      */
    public Polynomial(int a, int b) { 
        coef = new BigInteger[b+1];
        coef[b] = BigInteger.valueOf(a);
        deg = degree();
    }
    public Polynomial(BigInteger a, int b) { 
        coef = new BigInteger[b+1];
        coef[b] = a;
        deg = degree();
    }






    /** Return the degree of this polynomial (0 for the constant polynomial).
      */
    public int degree() {
        int d = 0;
        for (int i = 0; i < coef.length; i++)
            if (coef[i] != BigInteger.valueOf(0)) d = i;
        return d;
    }





    /** Return the sum of this polynomial and b, i.e., return c = this + b.
      */
    public Polynomial plus(Polynomial b) {
        Polynomial a = this;
        Polynomial c = new Polynomial(0, Math.max(a.deg, b.deg));
        for (int i = 0; i <= a.deg; i++) c.coef[i] = c.coef[i].add(a.coef[i]);
        for (int i = 0; i <= b.deg; i++) c.coef[i] = c.coef[i].add(b.coef[i]);

        c.deg = c.degree();
        return c;
    }






    /** Return the difference of this polynomial and b, i.e., return (this - b).
      */
    public Polynomial minus(Polynomial b) {
        Polynomial a = this;
        Polynomial c = new Polynomial(0, Math.max(a.deg, b.deg));
        for (int i = 0; i <= a.deg; i++) c.coef[i] = c.coef[i].add(a.coef[i]);
        for (int i = 0; i <= b.deg; i++) c.coef[i] = c.coef[i].subtract(b.coef[i]);

        c.deg = c.degree();
        return c;
    }






    /** Return the product of this polynomial and b, i.e., return (this * b).
      */
    public Polynomial times(Polynomial b) {
        Polynomial a = this;
        Polynomial c = new Polynomial(0, a.deg + b.deg);
        for (int i = 0; i <= a.deg; i++)
            for (int j = 0; j <= b.deg; j++)
                c.coef[i+j] = c.coef[i+j].add(a.coef[i].multiply(b.coef[j]));
        c.deg = c.degree();
        return c;
    }






    /** Return the composite of this polynomial and b, i.e., return this(b(x))  - compute using Horner's method.
      */
    public Polynomial compose(Polynomial b) {
        Polynomial a = this;
        Polynomial c = new Polynomial(0, 0);
        for (int i = a.deg; i >= 0; i--) {
            Polynomial term = new Polynomial(a.coef[i], 0);
            c = term.plus(b.times(c));
        }
        return c;
    }




    /** Return true whenever this polynomial and b are identical to one another.
      */
    public boolean equals(Polynomial b) {
        Polynomial a = this;
        if (a.deg != b.deg) return false;
        for (int i = a.deg; i >= 0; i--)
            if (a.coef[i] != b.coef[i]) return false;
        return true;
    }





    /** Evaluate this polynomial at x, i.e., return this(x).
      */
    public int evaluate(int x) {
        int p = 0;
        for (int i = deg; i >= 0; i--){
            coef[i] = coef[i].add(BigInteger.valueOf(x * p));
        p = coef[i].intValue();
    }
        return p;
    }






    /** Return the derivative of this polynomial.
      */
    public Polynomial differentiate() {
        if (deg == 0) return new Polynomial(0, 0);
        Polynomial deriv = new Polynomial(0, deg - 1);
        deriv.deg = deg - 1;
        for (int i = 0; i < deg; i++)
            deriv.coef[i] = coef[i + 1].multiply(BigInteger.valueOf(i+1));        
    return deriv;
    }





    /** Return a textual representationof this polynomial.
      */
    public String toString() {
        if (deg ==  0) return "" + coef[0];
        if (deg ==  1) return String.valueOf(coef[1]) + "x + " + String.valueOf(coef[0]);
        String s = String.valueOf(coef[deg]) + "x^" + deg;
        for (int i = deg-1; i > 0; i--) {
            if      (coef[i].intValue() == 0) continue;
            else if (coef[i].intValue()  > 0) s = s + " + " + ( coef[i].intValue());
            else if (coef[i].intValue()  < 0) s = s + " - " + (-coef[i].intValue());
            if      (i == 1) s = s + "x";
            else if (i >  1) s = s + "x^" + i;
        }
        return s;
    }






    public static void main(String[] args) {
        Polynomial zero = new Polynomial(1, 0);

        Polynomial p1   = new Polynomial(4, 3);
        Polynomial p2   = new Polynomial(3, 2);
        Polynomial p3   = new Polynomial(-1, 0);
        Polynomial p4   = new Polynomial(-2, 1);
        Polynomial p    = p1.plus(p2).plus(p3).plus(p4);   // 4x^3 + 3x^2  - 2x - 1

        Polynomial q1   = new Polynomial(3, 2);
        Polynomial q2   = new Polynomial(5, 0);
        Polynomial q    = q1.minus(q2);                     // 3x^2 - 5


        Polynomial r    = p.plus(q);
        Polynomial s    = p.times(q);
        Polynomial t    = p.compose(q);

        System.out.println("zero(x) =     " + zero);
        System.out.println("p(x) =        " + p);
        System.out.println("q(x) =        " + q);
        System.out.println("p(x) + q(x) = " + r);
        System.out.println("p(x) * q(x) = " + s);
        System.out.println("p(q(x))     = " + t);
        System.out.println("0 - p(x)    = " + zero.minus(p));
        System.out.println("p(3)        = " + p.evaluate(3));
        System.out.println("p'(x)       = " + p.differentiate());
        System.out.println("p''(x)      = " + p.differentiate().differentiate());


        Polynomial poly = new Polynomial();

        for(int k=0; k<=4; k++){
            poly = poly.times(new Polynomial(-k));
        }

        System.out.println(poly);
   }

}

3 个解决方案

#1


2  

So when you initialize your array of BigInteger, the values are null because you have specified an array of objects (if it was int[] then initial values are 0).

因此,当您初始化BigInteger数组时,值为null,因为您已指定了一个对象数组(如果它是int [],则初始值为0)。

As you can see from your constructor:

从构造函数中可以看出:

public Polynomial(int a, int b) { 
     coef = new BigInteger[b+1];
     coef[b] = BigInteger.valueOf(a);
     deg = degree();
}

You have only assigned coef[b], the other values remain null.

您只分配了coef [b],其他值保持为空。

Hence in first iteration of loop in method plus(Polynomial b), c.coef[0] is null hence NullPointerException when your loop tries to call c.coef[0].add(a.coef[0]).

因此,在方法加(多项式b)的循环的第一次迭代中,当你的循环试图调用c.coef [0] .add(a.coef [0])时,c.coef [0]为null,因此为NullPointerException。

Suggestion: define a method to initialize all the BigInteger values in an array to 0 to be consistent with declaration of int[] and call in your constructors. Example:

建议:定义一个方法,将数组中的所有BigInteger值初始化为0,以与int []的声明一致,并在构造函数中调用。例:

private static void initializeBigIntegerArray(BigInteger[] bigIntegers) {
   for (int i=0; i<bigIntegers.length; i++) {
      // So you don't overwrite anything you assign explicitly
      if (bigInteger[i] == null) {
         bigIntegers[i] = BigInteger.ZERO;
      }
   }
}

#2


1  

Recall that in Java an array of objects is actually an array of references to objects. So you need to create a BigInteger object for every array element. The entries you don't assign are not 0, they are null.

回想一下,在Java中,对象数组实际上是对象的引用数组。因此,您需要为每个数组元素创建一个BigInteger对象。您未分配的条目不为0,它们为空。

#3


1  

So in the plus method, you create this polynomial c whose backing array contains one zero, and several nulls. Then you go ahead and try to operate on all the coefficients in that polynomial, including all those nulls. So you're calling methods on variables for which an object hasn't been created yet, and that's what makes your null pointer problem.

因此在plus方法中,您创建此多项式c,其后备数组包含一个零和几个空值。然后你继续尝试对该多项式中的所有系数进行操作,包括所有那些空值。因此,您正在调用尚未创建对象的变量的方法,这就是使您的空指针出现问题的原因。

When you create each polynomial, make sure you have a BigInteger created for every entry in the backing array.

创建每个多项式时,请确保为后备阵列中的每个条目创建了一个BigInteger。

#1


2  

So when you initialize your array of BigInteger, the values are null because you have specified an array of objects (if it was int[] then initial values are 0).

因此,当您初始化BigInteger数组时,值为null,因为您已指定了一个对象数组(如果它是int [],则初始值为0)。

As you can see from your constructor:

从构造函数中可以看出:

public Polynomial(int a, int b) { 
     coef = new BigInteger[b+1];
     coef[b] = BigInteger.valueOf(a);
     deg = degree();
}

You have only assigned coef[b], the other values remain null.

您只分配了coef [b],其他值保持为空。

Hence in first iteration of loop in method plus(Polynomial b), c.coef[0] is null hence NullPointerException when your loop tries to call c.coef[0].add(a.coef[0]).

因此,在方法加(多项式b)的循环的第一次迭代中,当你的循环试图调用c.coef [0] .add(a.coef [0])时,c.coef [0]为null,因此为NullPointerException。

Suggestion: define a method to initialize all the BigInteger values in an array to 0 to be consistent with declaration of int[] and call in your constructors. Example:

建议:定义一个方法,将数组中的所有BigInteger值初始化为0,以与int []的声明一致,并在构造函数中调用。例:

private static void initializeBigIntegerArray(BigInteger[] bigIntegers) {
   for (int i=0; i<bigIntegers.length; i++) {
      // So you don't overwrite anything you assign explicitly
      if (bigInteger[i] == null) {
         bigIntegers[i] = BigInteger.ZERO;
      }
   }
}

#2


1  

Recall that in Java an array of objects is actually an array of references to objects. So you need to create a BigInteger object for every array element. The entries you don't assign are not 0, they are null.

回想一下,在Java中,对象数组实际上是对象的引用数组。因此,您需要为每个数组元素创建一个BigInteger对象。您未分配的条目不为0,它们为空。

#3


1  

So in the plus method, you create this polynomial c whose backing array contains one zero, and several nulls. Then you go ahead and try to operate on all the coefficients in that polynomial, including all those nulls. So you're calling methods on variables for which an object hasn't been created yet, and that's what makes your null pointer problem.

因此在plus方法中,您创建此多项式c,其后备数组包含一个零和几个空值。然后你继续尝试对该多项式中的所有系数进行操作,包括所有那些空值。因此,您正在调用尚未创建对象的变量的方法,这就是使您的空指针出现问题的原因。

When you create each polynomial, make sure you have a BigInteger created for every entry in the backing array.

创建每个多项式时,请确保为后备阵列中的每个条目创建了一个BigInteger。