在下面的代码中,我想找到2个多项式的最大公约数。 有时候我会收到错误#34; return c.plus((a.minus(b.times(c))。dividedes(b)));"。我该如何解决?
public Polynomial divides(Polynomial b) {
Polynomial a = this;
if ((b.deg == 0) && (b.coef[0] == 0))
throw new RuntimeException("Divide by zero polynomial");
if (a.deg < b.deg) return new Polynomial(0,0);
int coefficient = a.coef[a.deg]/(b.coef[b.deg]);
int exponent = a.deg - b.deg;
Polynomial c = new Polynomial(coefficient, exponent);
return c.plus( (a.minus(b.times(c)).divides(b)) );
}
public Polynomial GCD(Polynomial b) {
Polynomial a = this;
Polynomial f = b;
Polynomial x = a.minus((a.divides(f)).times(f));
if (x.deg == 0 && x.coef[0] == 0) {
return b;
}
return f.GCD(x);
}
答案 0 :(得分:0)
运行时异常意味着:您创建了无限递归。
最有可能的,因为你的方法 divides()在最后一行调用自己 - 没有在那里进行适当的检查以避免递归。
换句话说:你想要检查你的数学和那里的逻辑,以简单地避免 divides()不停地自我调用!