package test.demo2;
/**
* @author Dongguabai
* @date 2019/1/22 10:50
*/
public class NFactorial {
/**
* 迭代法
*
* @param n
* @return
*/
public static int method1(int n) {
if (n < 1) {
throw new RuntimeException("n must be a positive integer");
}
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
/**
* 递归法
*
* @param n
* @return
*/
public static int method2(int n) {
if (n < 1) {
throw new RuntimeException("n must be a positive integer");
}
if (n == 1) {
return n;
}
return n * method2(n - 1);
}
/**
* 递归法改进(尾递归:当递归调用是函数体中最后执行的语句并且它的返回值不属于表达式的一部分时,即就是调用自己,这个递归就是尾递归)
* (可以发现在上面的递归中在 n 过大的时候,计算过程中的栈帧也会非常的大);
* 尾递归肯定会创建栈帧,但是是可以复用栈帧(一个栈帧做完了所有的事情)。
* 编译器会检测到尾递归的形式并且进行优化,在函数调用前先把栈给设置好,调用完成后再恢复栈的这个操作
*
*/
public static int method3(int n, int result) {
if (n < 1) {
throw new RuntimeException("n must be a positive integer");
}
if (n == 1) {
return result;
}
//直接调用自身
return method3(n - 1, n * result);
}
}
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
简单的尾插法实现单链表
尾插法建立单链表
结点 头结点 链表 -
(递归)n的阶乘
1、递归求解阶乘
递归 阶乘 -
n!的阶乘(递归)
使用递归的思想写n!的阶乘
#include 递归 简易代码 -
mongodb在nacos配置
一、引言 上一篇文章,我介绍了如何在Linux系统上安装和配置MongoDB,其实都不是很难,不需要安装和编译,省去了Make && Make Install 命令的使用。我们既然介绍了在Linux系统(确切的说是CentOS 7上)上如何安装Mong
mongodb在nacos配置 数据库 操作系统 json Server