“斐波那契数列”的两种算法
 
斐波那契数列有个规律:从第三个数开始,每个数是前两个数之和,比如:
1 1 2 3 5 8 13 21 34 55......
 
现在通过两种方式(递归与非递归)算数列中第N个值,代码如下:
 
/**
* 斐波那契数列算法,从第三个数开始,每个数是前两个数之和:1 1 2 3 5 8 13 21 34 55
* 求第N个数的两种算法,分递归和非递归两种
*/

public class Fib {
        public static void main(String[] args) {
                System.out.println(f(20));
                System.out.println(fx(20));
        }

        //递归方式
        public static int f(int n) {
                //参数合法性验证
                if (n < 1) {
                        System.out.println("参数必须大于1!");
                        System.exit(-1);
                }
                if (n == 1 || n == 2) return 1;
                else return f(n - 1) + f(n - 2);
        }

        //非递归方式
        public static int fx(int n) {
                //参数合法性验证
                if (n < 1) {
                        System.out.println("参数必须大于1!");
                        System.exit(-1);
                }
                //n为1或2时候直接返回值
                if (n == 1 || n == 2) return 1;

                //n>2时候循环求值
                int res = 0;
                int a = 1;
                int b = 1;
                for (int i = 3; i <= n; i++) {
                        res = a + b;
                        a = b;
                        b = res;
                }
                return res;
        }
}
 
运行结果:
6765
6765

Process finished with exit code 0
 
还是递归的代码简单些,不过递归总体来说是以空间换时间,速度快,耗内存。
非递归比较省内存,速度稍微慢些。