斐波那契数列

来源:互联网 发布:装修公司软件 编辑:程序博客网 时间:2024/06/05 16:12
“斐波那契数列”的两种算法
 
斐波那契数列有个规律:从第三个数开始,每个数是前两个数之和,比如:
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; 
        } 
}
0 0
原创粉丝点击