In this section:
a=b;
b=a+b;
you're assigning b
to a+b
, but a
is already b
. So really you're doubling b
Easiest solution is a temp variable:
public static int fib2(int n){
int a = 0;
int b =1;
while(n-- >0){
int old_a;
old_a = a;
a=b;
b=old_a+b;
}
return a;
}
In python, a, b = b, a + b
stores an intermediate tuple
automatically before assigning the new values to the variables, while in Java you need to be explicit about it
Breaking down Python's instructions, a, b = b, a + b
is executing this disassembly:
5 17 LOAD_FAST 1 (b)
20 LOAD_FAST 0 (a)
23 LOAD_FAST 1 (b)
26 BINARY_ADD
27 ROT_TWO
28 STORE_FAST 0 (a)
31 STORE_FAST 1 (b)
In a simpler sense, staying python, here's the process:
temp_tuple = (b, a + b)
a, b = temp_tuple