定义
迭代法又称辗转法,是一种不断用变量的旧值递推新值的过程。
代码示例
public class Iteration {
/**
* 斐波那契数列如下
* 1,1,2,3,5,8,13,21,34....
* <p>
* 规律为从第3位开始,每一位数字都是上两位数字之和
*/
public static long fib(int n) {
long pre = 1l;
long current = 1l;
long next;
if (n == 1 || n == 2) {
return 1;
} else {
for (int i = 3; i <= n; i++) {
next = current;
current = current + pre;
pre = next;
}
}
return current;
}
public static void main(String[] args) {
System.out.println(fib(1));
System.out.println(fib(2));
System.out.println(fib(3));
System.out.println(fib(4));
System.out.println(fib(5));
}
}
网友评论