J027_递归算法

一、求n的阶乘

n的阶乘:1*2*3*4*...*n

package com.itheima.d01_file;

public class DiguiTest1 {
    public static void main(String[] args) {
        //求n的阶乘
        System.out.println(f(3));
        System.out.println(f(4));
        System.out.println(f(5));
    }

    private static int f(int n) {
        if (n == 1) {
            return 1;
        } else {
            return f(n - 1) * n;
        }
    }
}

二、求1+2+...+n的和

package com.itheima.d01_file;

public class DiguiTest2 {
    public static void main(String[] args) {
        //求1+2+...+n的和
        System.out.println(f(3));
        System.out.println(f(4));
        System.out.println(f(5));
    }

    private static int f(int n) {
        if (n == 1) {
            return 1;
        } else {
            return f(n - 1) + n;
        }
    }
}

三、猴子吃桃

3.1 题目描述

猴子第一天摘下若干桃子,当即吃了一半,觉得好不过瘾,于是又多吃了一个。第二天又吃了前天剩余桃子数量的一半,觉得好不过瘾,于是又多吃了一个。以后每天都是吃前天剩下桃子数量的一半,觉得好不过瘾,又多吃了一个。等到第10天的时候,发现桃子只有1个了。

请问桃子第一天摘了多少桃子?

3.2 分析

假设第一天摘的桃子数为f(x),第二天的桃子数为f(x+1),则有f(x) - f(x)/2 -1 = f(x+1)

变换格式后:f(x) = 2 * f(x+1) + 2

3.3 代码实现

package com.itheima.d01_file;

public class DiguiTest3 {
    public static void main(String[] args) {
        System.out.println(f(1));
        System.out.println(f(2));
        System.out.println(f(3));
    }

    private static int f(int n) {
        if (n == 10) {
            return 1;
        } else {
            return 2 * f(n + 1) + 2;
        }
    }
}

3.4 运行结果

相关推荐

  1. ---算法

    2024-07-14 20:54:03       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-14 20:54:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-14 20:54:03       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-14 20:54:03       58 阅读
  4. Python语言-面向对象

    2024-07-14 20:54:03       69 阅读

热门阅读

  1. ISA95-Part5-安全和权限管理的设计思路

    2024-07-14 20:54:03       22 阅读
  2. 前端请求整合

    2024-07-14 20:54:03       17 阅读
  3. 2024.7.13 刷题总结

    2024-07-14 20:54:03       22 阅读
  4. 安卓热门面试题二

    2024-07-14 20:54:03       19 阅读
  5. 单元化(Cell Sharding)

    2024-07-14 20:54:03       21 阅读
  6. 网络安全-网络设备及其配置1

    2024-07-14 20:54:03       22 阅读
  7. C++指针

    2024-07-14 20:54:03       24 阅读
  8. Tensor-LLM简单介绍

    2024-07-14 20:54:03       22 阅读