Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci using 1 variable

Tags:

java

I was asked the following question in an interview:

Is there any way in which Fibonacci series can be generated using only 1 variable ?

I didn't know what to answer. What should I have said?

like image 254
GoodSp33d Avatar asked Jul 15 '10 11:07

GoodSp33d


People also ask

What is the Fibonacci sequence pattern?

The Fibonacci sequence is a set of integers (the Fibonacci numbers) that starts with a zero, followed by a one, then by another one, and then by a series of steadily increasing numbers. The sequence follows the rule that each number is equal to the sum of the preceding two numbers.


1 Answers

Yes, you can used the closed-form expression:

where

You can calculate the expression using a double and round the result to the nearest integer. Because of the finite precision of floating point arithmetic this formula will give a wrong answer for large enough n, but I think it will work in the case when the result fits into a Java 32-bit integer.

like image 147
Mark Byers Avatar answered Sep 19 '22 11:09

Mark Byers