Efficient algorithm fibonacci sequence

Problem :   write efficient algorithm that return fibonacci sequence

Well that's simple according to wikipedia : https://en.wikipedia.org/wiki/Fibonacci_number

all i need to do the following 1+2=3 new number then 2+3 =5 then 3+5=8 and so on .

thinking fast it's pretty easy is that real interview question ! yes it's and you can asked question like this in big companies such as google,facebook,etc .

you wrote working code like this one


public static long fiboexample(long number){
  if(number==1 || number== 2){
   return 1;
  }
  return fiboexample(number -1 ) + fiboexample(number -2);
 }

What's wrong with this code can you guess ? well it's simple performance issue now every element in sequence depend on other elements and waiting them for example 

5 wait 2+3 
8 wait 5+3
13 wait 5+8

and so on what do you notice here 3 duplicates two times and five also so on with this code duplication comes greater than acceptable when input for e.g 2^10

recursion function working good with simple input but in corner cases and large input it should fail .

So !


package Other;
/**
 *  write efficient algorithm that return fibonacci sequence 
 * @author Mohamed fawzy
 * @copyright GPL
 */
public class FibonacciSequence {
 
 /**
  * 
  * @param number
  * @return sequence of numbers 
  */
 public static long fibonacci(long number){
  int[] result = {1,2};
  if(number < 2){
   return result[(int) number];
  }
  long fibNumberOne=1;
  long fibNumberTwo=0;
  long fibNumber=0;
  for(int i=2; i<=number; ++i){
   fibNumber = fibNumberOne + fibNumberTwo;
   fibNumberTwo = fibNumberOne;
   fibNumberOne = fibNumber;
  }
  return fibNumber;
 }
 

}

Test case

package Other;

public class FibonacciSequenceTest {
 
 
 public static void main(String[] args){
  FibonacciSequence FibonacciSequence = new FibonacciSequence();
  for(int i=2; i<=10; i++){
   System.out.println( FibonacciSequence.fibonacci(i) );
  }
 }
}

Comments

Popular Posts