-4

so my work was to convert this method:

long fib(long n) {
long i = -1, a = 0, b = 1;
while (++i != n)
b = a + (a = b);
return a;
}

into another iterative fibonacci method that still does the EXACT same just with the difference that the new one is only allowed to contain simple instructions/assignments (but in this context the while loop is also allowed).

So I made this method:

  public static long fib2(long n){
        long i = 0;
        long a = 0;
        long b = 1;
        while (i != n){
            long oldA = a;
            a = b;
            b = oldA + a;
            ++i;
        }
        return a;
    }

My question now is: Is it possible to simplify the method and still only keep all the old variables from the 1st method (n, i, a, b) or do I HAVE TO create a new variable (in my case oldA) therefore. Because if it would be possible to do it only with the old variables then that would be better but I don't know how.

I'm asking all this because in the next step I need to find the loop invariant for this method and I think its easier if I just have the given variables and don't add new ones. (I think not sure tho).

Thx in advance.

EgZoShift
  • 29
  • 5
  • 2
    You need provide a example to describe what `simplify ` you mean. I don't think `fib2` is simplier than `fib1`. – vipcxj Jan 14 '21 at 01:53
  • So you want a method that does the same except it's not like ```fib1``` and doesn't want to create new variables? – lier wu Jan 14 '21 at 01:55
  • 1
    Basically I think it means one line should only be allowed to do one thing. Lke f.ex. increment sth or have a comparison etc. but not both – EgZoShift Jan 14 '21 at 02:00
  • 1
    @EgZoShift ok, see my answer – lier wu Jan 14 '21 at 02:01
  • 1
    Yh I saw it thanks a lot tho. Already had the b+= a part but I didnt rly know how to set a to the correct value after – EgZoShift Jan 14 '21 at 02:03

1 Answers1

1

Ok, so you want to keep all the old variables from the 1st method(fib1), then:

  public static long fib3(long n){
        long i = 0;
        long a = 0;
        long b = 1;
        while (i != n){
            b += a;
            a = b - a;//since now b(the variable) is a + b, and a + b - b = a
            i++; 
        }
        return a;
    }

Or in loop:

  public static long fib3(long n){
        long a = 0;
        long b = 1;
        for(long i = 0;i<n;i++){
            b += a;
            a = b - a;//since now b(the variable) is a + b, and a + b - b = a
        }
        return a;
    }
lier wu
  • 620
  • 7
  • 23