简体   繁体   中英

Iteration for negative integers

I have written a iterative function to generate result for expression:

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;
      }
}

Can I modify the function to get result for negative integers as well ?

This is a simple math problem:

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

thus

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

Substitute n = k+2 and get:

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

Thus you can calculate your function having two subsequent numbers as well. Here's the updated code:

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;
    }
}

The results from -10 to 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

You can easily check that your original condition holds for negative numbers as well. For example

F(0) = 3*F(-1)+F(-2)+0 = 3*(-11)+37+0 = 4

If your method is not meant to work with negative values, then you can blame the caller for passing a negative value. Simply throw an InvalidParameterException when n is negative.

public int calculate(int n){
    if (n < 0){
        throw new InvalidParameterException("Negative parameter");
    }
    //... proceed as usual
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM