1

我编写了一个迭代函数来生成表达式结果:

F(n) = 3*F(n-1)+ F(n-2) + n

public int calculate(int n){
      if(n == 0) {
         return 4;
      }
      if(n ==1){
          return 2;
      }
      else {
          int f=0;
          int fOne = 4;
          int fTwo = 2;
          for (int i=2;i<=n;i++) {
              f = 3*fOne + fTwo + i;
              fTwo = fOne;
              fOne = f;                 
          }
          return f;
      }
}

我可以修改函数以获得负整数的结果吗?

4

2 回答 2

0

这是一道简单的数学题:

F(n) = 3*F(n-1)+F(n-2)+n

因此

F(n-2) = F(n)-3*F(n-1)-n

代入n = k+2并得到:

F(k) = F(k+2)-3*F(k+1)-k-2

因此,您也可以计算具有两个后续数字的函数。这是更新的代码:

public int calculate(int n) {
    if (n == 0) {
        return 4;
    }
    if (n == 1) {
        return 2;
    } else if (n < 0) {
        int f = 0;
        int fOne = 4;
        int fTwo = 2;
        for (int i = -1; i >= n; i--) {
            f = fTwo - 3 * fOne - i - 2;
            fTwo = fOne;
            fOne = f;
        }
        return f;
    } else {
        int f = 0;
        int fOne = 4;
        int fTwo = 2;
        for (int i = 2; i <= n; i++) {
            f = 3 * fOne + fTwo + i;
            fTwo = fOne;
            fOne = f;
        }
        return f;
    }
}

从 -10 到 9 的结果:

-10: 520776
-9: -157675
-8: 47743
-7: -14453
-6: 4378
-5: -1324
-4: 402
-3: -121
-2: 37
-1: -11
0: 4
1: 2
2: 16
3: 55
4: 185
5: 615
6: 2036
7: 6730
8: 22234
9: 73441

您可以轻松地检查您的原始条件是否也适用于负数。例如

F(0) = 3*F(-1)+F(-2)+0 = 3*(-11)+37+0 = 4
于 2015-09-15T03:24:06.360 回答
-1

如果您的方法不适用于负值,那么您可以责怪调用者传递了负值。InvalidParameterException当 n 为负时简单地抛出一个。

public int calculate(int n){
    if (n < 0){
        throw new InvalidParameterException("Negative parameter");
    }
    //... proceed as usual
}
于 2015-09-15T03:10:07.710 回答