Java中的阶乘


/**
 * Description:阶乘 0! = 1,n! = (n-1)! * n;
 */
public class Factorial {

    public static int fac(int n){
        if(n == 0 | n == 1) return 1;
        if(n > 1) return fac(n-1)*n;
        else throw  new IllegalArgumentException("参数错误");
    }
    public static int fact(int n){
        int sum = 1;
        if (n == 0 | n == 1) return sum;
        if (n > 1){
            for (int i = 1; n >= i; i++){
                sum *= i;
            }
        } else throw new IllegalArgumentException("参数错误");
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(fac(6));
        System.out.println(fact(6));
    }
}
posted @   希望在田野上  阅读(366)  评论(0编辑  收藏  举报
编辑推荐:
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
阅读排行:
· C# 13 中的新增功能实操
· Vue3封装支持Base64导出的电子签名组件
· 万字长文详解Text-to-SQL
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
点击右上角即可分享
微信分享提示