阶乘 及 斐波那契数列

阶乘:
一个正整数的阶乘是所有小于及等于该数的正整数的积,并且0的阶乘为1。
实例学习:

public class Factorial_Test {

    public static void main(String[] args) {
        int result = factorial(6);
        System.out.println(result);
    }

    public static int factorial(int index) {
        if (index >= 0) {
            if (index == 0) {
                return 1;
            } else if (index == 1) {
                return 1;
            } else {
                return index * factorial(index - 1);
            }

        } else {
            System.out.println("请重新输入");
            return -1;
        }
    }

}
运行结果:
720

斐波那契数列:又称黄金分割数列,指的是这样一个数列:1、1、2、3、5、8、13、21、34、……在数学上,斐波纳契数列以如下被以递归的方法定义:F(0)=0,F(1)=1, F(n)=F(n-1)+F(n-2)(n>=2,n∈N*)

实例学习:

public class Fibonacci_sequence {

    public static void main(String[] args) {
        int result = fibonse(6);
        System.out.println(result);
        System.out.println("------------");
        int result1 = fibonse(0);
        System.out.println(result1);
        System.out.println("------------");
        int result2 = fibonse(-6);
        System.out.println(result2);

    }

    public static int fibonse(int index) {
        if (index >= 0) {
            if (index == 0) {
                return 0;
            } else if (index == 1) {
                return 1;
            } else {
                return fibonse(index - 1) + fibonse(index - 2);
            }

        } else {
            System.out.println("请重新输入");
            return -1;
        }
    }
}
运行结果:
8

------------
0

------------
请重新输入
-1

每档一语:
生活就像海洋,只有意志将强的人才能到达彼岸。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值