Archive for January, 2015

 

Fibonacci algorithm iterative

Jan 28, 2015 in Algorithms

from
http://www.csd.uwo.ca/courses/CS1027b/code/FibonacciDemo.java

[java]

/** Method to calculate the nth Fibonacci number iteratively.
* @param n
* @return nth Fibonacci number
* precondition: n >= 1
*/
public static long ifib(long n) {
if (n &lt 2) {
return 1;
} else {
long prev = 1, current = 1, next = 0;
for (long i = 3; i &lt= n; i++) {
next = prev + current;
prev = current;
current = next;
}
return next;
}
}

[/java]

Fibonacci algorithm recursive

Jan 28, 2015 in Algorithms

from http://javadecodedquestions.blogspot.com/2013/01/java-interviews-frequently-asked-puzzles.html

[java]

public class FibonacciNumber {
public static int fibonacci(int n) {
if (n < 2) {
return n;
}
else {
return fibonacci(n – 1) + fibonacci(n – 2);
}
}
}

[/java]

from http://stackoverflow.com/questions/8965006/java-recursive-fibonacci-sequence

[java]

public int fibonacci(int n) {
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return fibonacci(n – 1) + fibonacci(n – 2);
}

[/java]