【问题标题】:Receives one integer and returns the factorial of the number passed接收一个整数并返回传递的数字的阶乘
【发布时间】:2019-03-10 14:14:48
【问题描述】:

创建两个单独的包数学和应用程序。在任一类中都有一个名为 MathHelper 和 Application 的类。我需要将静态方法添加到名为 factorial(int) 的 MathHelper.java 类中,该类接收一个整数并返回传递的数字的阶乘。一个 main 方法被添加到应用程序并调用 Mathhelper.factorial。这是我到目前为止的代码......

public class Application {

    public static void main(String[]args) {

       System.out.println(MathHelper.doubleInt((9)));   
    }
}

public class MathHelper {
    public static void main(String[]args) {
    }
    public static int fact(int factNum) {
        if (factNum==1) {   
            return 1;
        }
        else {
            return factNum + (fact(factNum - 1));
        }
    }
}

【问题讨论】:

  • 我认为这是正确的总体思路,但 + 必须是 * - 阶乘意味着将大量数字相乘,而不是相加。

标签: java package factorial


【解决方案1】:

您可以使用以下方法计算阶乘:

循环:

public long fact(int factNum) {
    long fact = 1;
    for (int iteration = 2; iteration <= factNum; iteration++) {
        fact = fact * iteration;
    }
    return fact;
}

流:

public long fact(int factNum) {
    return LongStream.rangeClosed(1, factNum)
            .reduce(1, (long fact, long iteration) -> fact * iteration);
}

递归:

public long fact(int factNum) {
    if (factNum <= 2) {
        return factNum;
    }
    return factNum * fact(factNum - 1);
}

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2018-10-16
    • 2014-03-24
    • 2019-05-22
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    相关资源
    最近更新 更多