How to implement Fibonacci numbers in JAVA

Fibonacci numbers are also know as Fibonacci sequence or Fibonacci series.

The Fibonacci sequence is represented by a sequence of numbers, starting with 0 and 1, in which the next element is the sum of the preceding two elements. For instance, the following sequence:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144

represent a sequence of 13 Fibonacci numbers.

One common problem in computer programming is to print the first n elements in Fibonacci sequence. The solution can be implemented using an iterative algorithm or an recursive one. The recursive implementation of this problem in Java is as follow:

Of course, the above example is an inefficient one, as it is very slow (set a value greater than 50 and you will notice). Also the 93rd Fibonacci number will overflow a long.

The iterative implementation of the same problem could be as follow:

Note that the same remark as for the recursive implementation remain valid: the 93rd Fibonacci number will overflow the long. Instead, you will notice that the implementation is faster.

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Reply