用Java语言的递归实现斐波那契序列、阶乘、阶乘的阶乘

本文介绍了如何使用Java语言通过递归方法实现斐波那契序列、阶乘及阶乘的阶乘。斐波那契序列遵循每个数是前两个数之和的规则,递归实现需设定终止条件和递归主体。具体代码实现虽未展示,但读者可期待详细步骤和逻辑解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

斐波那契序列:

  1. 规则:当前这个数值,等于其当前两位数值的和,示例如:1 1 2 3 5 8 13
  2. 实现方法:递归实现
  3. 递归实现的要点:
    终止条件
    循环主体
  4. 具体代码实现:
//------斐波那契------------
class FiberTest{
 public static int fiber (int location){
  if (location<1){
   return -1;
  }
  if (location == 1 || location == 2 ){
   return 1;
  }
  else{
   return fiber(location-1)+fiber(-2);
  }
 }
 public static void main(String[] args) {
  System.out.println(fiber(-100));
  System.out.println(fiber(1));
  System.out.println(fiber(2));
  System.out.println(fiber(5));
  System.out.println(fiber(7));
 }
}

在这里插入图片描述

---------阶乘------------
class FacTest{
 public static long fac (int n){
  if (n < 1){
   return -1;
  }
  if (n == 1){
   return 1;
  }
  else {
   return n*fac(n-1);
  }
 }
 public static void main(String[] args) {
  System.out.println(fac(-3));
  System.out.println(fac(1));
  System.out.println(fac(2));
  System.out.println(fac(5));
 }
}
```

在这里插入图片描述

//------阶乘的阶乘---------
class FacFacTest{
public static long fac(int n){
 if (n<1){
  return -1;
 }
 if(n == 1){
  return 1;
 }
 else {
  return n*fac(n - 1);
 }
  }
public static long facFac(int n){
 if(n < 1){
  return -1;
 }
 if (n == 1 ) {
  return 1;
 }
 else {
  return fac(n)*facFac(n - 1);
 }
  }
public static void main (String[] args){
 System.out.println(facFac(-3));
 System.out.println(facFac(1));
 System.out.println(facFac(2));
 System.out.println(facFac(5));
}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值