Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fibonacci works in python but fails in Java

Tags:

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

like image 620
eagertoLearn Avatar asked Feb 05 '14 18:02

eagertoLearn


People also ask

Is Fibonacci method in Java?

Fibonacci Series Using Recursion in JavaThe Java Fibonacci recursion function takes an input number. Checks for 0, 1, 2 and returns 0, 1, 1 accordingly because Fibonacci sequence in Java starts with 0, 1, 1. When input n is >=3, The function will call itself recursively. The call is done two times.

How the Fibonacci sequence works in Python?

We initialize the first term to 0 and the second term to 1. If the number of terms is more than 2, we use a while loop to find the next term in the sequence by adding the preceding two terms. We then interchange the variables (update it) and continue on with the process.

Does Python have a Fibonacci sequence?

Fibonacci Sequence can be implemented both iteratively and recursively in Python. For both examples, try changing the value of the argument passed to the function to print out more numbers in the sequence.


1 Answers

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
like image 114
mhlester Avatar answered Oct 24 '22 06:10

mhlester