Author: techfox9

Fibonacci algorithm iterative

Wednesday, January 28th, 2015 @ 1:30 am

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]

Algorithms


 


Comments are closed.