Fibonacci Sequences

Recursive (bad performance):

class Fibonacci{

public int getFibonacci(int n){

if(n==0) return 0;

if(n==1) return 1;

return getFibonacci(n-1) + getFibonacci(n-2)

}

}

Iterative ( O(n) )

class Fibonacci{

public int getFibonacci(int n){

int firstNumber = 0; int secondNumber = 1;

int total = 0;

for(int i = 0; i<=n; i++){

total = firstNumber + secondNumber;

firstNumber = secondNumber;

secondNumber = total;

}

}

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s