fibonacci works in python but fails in Java
fibonacci, java, python
Solution
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
Problem
I have this code for calculating `fibonacci` number in `python`. It works and gives the expected result. but when I translated the same to `Java`, it fails. Any idea of what is going wrong here? In `python`: ``` def fib3(n): a,b=0,1 while n>0: a,b=b,a+b n-=1 return a ``` `fib3(12) --> 144` In `Java`: ``` public static int fib2(int n){ int a = 0; int b =1; while(n-- >0){ a=b; b=a+b; } return a; } ``` `fib2(12) --> 2048`