首页 > 代码库 > 递归:阶乘、斐波那契数列

递归:阶乘、斐波那契数列

  • 阶乘
技术分享
    public static void main(String[] args) {
        System.out.println(factorial(5));;
    }
    //factorial 阶乘
    public static long factorial(int n) {
        if (n == 1) {
            return 1;
        }
        return n*factorial(n-1);
    }
View Code
  • 阶乘画图理解

技术分享

  •  斐波那契数列递归实现:
技术分享
    public static void main(String[] args) {
        System.out.println(Fibonacci(15));
    }
    //Fibonacci 斐波那契数列
    public static long Fibonacci(int n) {
        if (n == 1 || n == 2) {
            return 1;
        }
        return Fibonacci(n-1)+Fibonacci(n-2);
    }
View Code
  • 斐波那契数列循环实现:
技术分享
    public static void main(String[] args) {
        System.out.println(Fibonacci(40));
    }
    //Fibonacci 斐波那契数列
    public static long Fibonacci(int index) {
        if (index == 1 || index == 2) {
            return 1;
        }
        long first = 1, second = 1, result = 0;
        for (int i=3; i<index+1; i++) {
            result = first + second ;
            first = second;
            second = result;
        }
        return result;
    }
View Code
  • 画图理解斐波那契数列:

技术分享

 

递归:阶乘、斐波那契数列