Java 实现 N 的阶乘及尾递归改进

版权声明: https://blog.csdn.net/Dongguabai/article/details/86591097
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);
    }
}

参考资料:

https://blog.csdn.net/azhegps/article/details/72638906

猜你喜欢

转载自blog.csdn.net/Dongguabai/article/details/86591097
今日推荐