1
도움 감사합니다. 이 클래스의 모든 것을 compose 메서드를 제외하고 BigInteger 형식으로 수정하는 작업을 마칠 수있었습니다. 누가 왜이 부분이 제대로 작동하지 않는지에 관해 나를 도울 수 있습니까? 고마워. 고마워. 그것이 당신의 디폴트 메커니즘에 일치하지 않는 내가 문제라고 생각 무엇어떻게 BigInteger를 사용하여 다항식 클래스에서이 "더하기"메서드를 수정할 수 있습니까?
import java.math.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] = new BigInteger("1");
deg = 0;
}
/** Creates the linear polynomial of the form P(x) = x + a.
*/
public Polynomial(int a){
coef = new BigInteger[2];
coef[1] = new BigInteger("1");
coef[0] = new BigInteger(Integer.toString(a));
deg = 1;
}
/** Creates the polynomial P(x) = a * x^b.
*/
public Polynomial(int a, int b) {
coef = new BigInteger[b+1];
for(int i = 0; i < b; i++){
if(coef[i] == null)
coef[i] = new BigInteger("0");
}
coef[b] = new BigInteger(Integer.toString(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] != null) d = i; // check to make sure this works
return d;
}
/** 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].intValue(), 0);
c = term.plus(b.times(c));
}
return c;
}
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 a textual representation of this polynomial.
*/
public String toString() {
if (deg == 0) return "" + coef[0];
if (deg == 1) return coef[1] + "x + " + coef[0];
String s = coef[deg] + "x^" + deg;
for (int i = deg-1; i >= 0; i--) {
if (coef[i] == null) continue;
else if (coef[i].intValue() > 0) s = s + " + " + (coef[i]);
else if (coef[i].intValue() < 0) s = s + " - " + (coef[i].negate());
if(coef[i].intValue() != 0)
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
}
public static void main(String[] args) {
Polynomial p = new Polynomial(1,2);
Polynomial q = new Polynomial(2,3);
Polynomial t = p.compose(q); // incorrect
System.out.println("p(q(x)) = " + t); // incorrect
}
}
가 함께 게시물을 업데이트하십시오 재정의 된'toString() '다항식도 출력합니다 – PopoFibo
디버거를 사용하여 문제의 원인을 보았습니까? 버그가있는'toString'이 아니라'plus'인지 알고 계십니까? –
죄송합니다 @PopoFibo, 위의 코드를 편집하여 toString() 메서드를 포함 시켰습니다. 버그가있는 toString() 메서드 또는 plus() 메서드 일 수 있습니다. 디버거에서 그걸 가지고 놀면 마치 toString()처럼 보이지만 문제가 무엇인지 알 수는 없습니다. – user3268401