递归的使用(问题较小),数据太大递归速度非常慢

这篇博客展示了如何使用递归算法分别计算100的和与5的阶乘。在`MyFactorialDemo1`中,作者实现了递归求和,每次调用方法时,变量会更接近出口,以此防止栈内存溢出。而在`MyFactorialDemo2`中,递归地计算了5的阶乘。这两个实例都强调了正确设计递归出口的重要性,以确保程序的稳定性和效率。
摘要由CSDN通过智能技术生成

每次调用方法,变量会与出口更接近,写好出口,防止栈内存溢出。

1.求和

package com.hncu.myfactorial;

public class MyFactorialDemo1 {
    //递归求100的和
    public static void main(String[] args) {
        System.out.println(sums(100));
    }
    public static int sums(int i){
        if (i == 1){
            return 1;
        }
        else {
            return i + sums(i - 1);
        }
    }
}

2.阶乘

package com.hncu.myfactorial;

public class MyFactorialDemo2 {
    //递归求5的阶乘
    public static void main(String[] args) {
        int result = getresult(5);
        System.out.println(result);
    }

    private static int getresult(int i) {
        if (i == 1) {
            return 1;
        } else {
            return i * getresult(i - 1);
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值