我的目标是提供一个类 Stacker,其中包含一个方法 stackSize,该方法以一个名为 extension 的 int 作为其参数。它应该返回最小的 long n,使得序列 1/2 + 1/4 + 1/6 + 1/8 + ... + ... + 1/2n 的总和大于或等于扩展。
假设我的 Rat 类(有理数)正确地将两个分数相加,使用第一个参数作为分子,第二个参数作为分母,有什么想法为什么这段代码对我不起作用?
默认的 Rat() 构造函数只生成有理数 (0/1),而 Rat(extension) 构造函数生成有理数 (extension/1)。
public class StackerTest {
@Test
public void test1()
{
assertEquals(4, Stacker.stackSize(1));
}
}
当我运行测试用例时:
@Test
public void test1()
{
assertEquals(4, Stacker.stackSize(1));
}
它在给出 IllegalArgumentException 之前运行了 30 秒
这是 Rat 类的构造函数以及 add 方法
/**
* If d is zero, throws an IllegalArgumentException. Otherwise creates the
* rational number n/d
*/
public Rat (int n, int d)
{
// Check parameter restriction
if (d == 0)
{
throw new IllegalArgumentException();
}
// Adjust sign of denominator
num = n;
den = d;
if (den < 0)
{
num = -num;
den = -den;
}
// Zero has a standard representation
if (num == 0)
{
den = 1;
}
// Factor out common terms
int g = gcd(Math.abs(num), den);
num = num / g;
den = den / g;
}
/**
* Returns the sum of this and r
*/
public Rat add (Rat r)
{
int firstNum = this.num*r.den;
int firstDen = this.den*r.den;
int secondNum = r.num*this.den;
int secondDen = r.den*this.den;
Rat x = new Rat(firstNum+secondNum, firstDen);
return x;
}