有没有一种方法可以在 Java 中计算阶乘?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/891031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:45:06  来源:igfitidea点击:

Is there a method that calculates a factorial in Java?

java

提问by

I didn't find it, yet. Did I miss something? I know a factorial method is a common example program for beginners. But wouldn't it be useful to have a standard implementation for this one to reuse? I could use such a method with standard types (Eg. int, long...) and with BigInteger / BigDecimal, too.

我还没找到呢 我错过了什么?我知道阶乘方法是初学者常见的示例程序。但是有一个标准实现来重用这个实现不是很有用吗?我可以在标准类型(例如 int、long...)和 BigInteger / BigDecimal 中使用这样的方法。

采纳答案by Karl the Pagan

I don't think it would be useful to have a library function for factorial. There is a good deal of research into efficient factorial implementations. Here is a handful of implementations.

我认为为阶乘提供库函数没有用。有大量关于有效阶乘实现的研究。这里有一些实现。

回答by bdonlan

Although factorials make a nice exercise for the beginning programmer, they're not very usefulin most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.

尽管阶乘对于初学者来说是一个很好的练习,但它们在大多数情况下并不是很有,而且每个人都知道如何编写阶乘函数,因此它们通常不在普通库中。

回答by Igor Krivokon

Bare naked factorials are rarely needed in practice. Most often you will need one of the following:

在实践中很少需要裸阶乘。大多数情况下,您将需要以下其中一项:

1) divide one factorial by another, or

1) 将一个阶乘除以另一个,或

2) approximated floating-point answer.

2) 近似浮点答案。

In both cases, you'd be better with simple custom solutions.

在这两种情况下,您最好使用简单的自定义解决方案。

In case (1), say, if x = 90! / 85!, then you'll calculate the result just as x = 86 * 87 * 88 * 89 * 90, without a need to hold 90! in memory :)

在情况 (1) 中,假设 x = 90!/ 85!,那么您将像 x = 86 * 87 * 88 * 89 * 90 一样计算结果,而无需保留 90!在记忆中 :)

In case (2), google for "Stirling's approximation".

在情况 (2) 中,谷歌搜索“斯特林近似值”。

回答by R Ubben

The only business use for a factorial that I can think of is the Erlang B and Erlang C formulas, and not everyone works in a call center or for the phone company. A feature's usefulness for business seems to often dictate what shows up in a language - look at all the data handling, XML, and web functions in the major languages.

我能想到的阶乘的唯一商业用途是 Erlang B 和 Erlang C 公式,并不是每个人都在呼叫中心或电话公司工作。功能对业务的有用性似乎通常决定了语言中显示的内容 - 查看主要语言中的所有数据处理、XML 和 Web 功能。

It is easy to keep a factorial snippet or library function for something like this around.

很容易为这样的东西保留一个阶乘片段或库函数。

回答by Bill the Lizard

Apache Commons Mathhas a few factorial methods in the MathUtilsclass.

Apache Commons MathMathUtils类中有一些阶乘方法。

回答by Valentin Rocher

Apache Commons Math package has a factorial method, I think you could use that.

Apache Commons Math 包有一个阶乘方法,我想你可以使用它。

回答by saroj adhikari

public class UsefulMethods {
    public static long factorial(int number) {
        long result = 1;

        for (int factor = 2; factor <= number; factor++) {
            result *= factor;
        }

        return result;
    }
}

Big Numbers version by HoldOffHunger:

HoldOffHunger 的Big Numbers 版本:

public static BigInteger factorial(BigInteger number) {
    BigInteger result = BigInteger.valueOf(1);

    for (long factor = 2; factor <= number.longValue(); factor++) {
        result = result.multiply(BigInteger.valueOf(factor));
    }

    return result;
}

回答by dogbane

Use Guava's BigIntegerMathas follows:

使用番石榴的BigIntegerMath如下:

BigInteger factorial = BigIntegerMath.factorial(n);

(Similar functionality for intand longis available in IntMathand LongMathrespectively.)

(对于类似的功能intlong可在IntMathLongMath分别)。

回答by Feri

Short answer is: use recursion.

简短的回答是:使用递归。

You can create one method and call that method right inside the same method recursively:

您可以创建一个方法并在同一方法中递归调用该方法:

public class factorial {

    public static void main(String[] args) {
        System.out.println(calc(10));
    }

    public static long calc(long n) {
        if (n <= 1)
            return 1;
        else
            return n * calc(n - 1);
    }
}

回答by midnite

i believe this would be the fastest way, by a lookup table:

我相信这将是最快的方式,通过查找表:

private static final long[] FACTORIAL_TABLE = initFactorialTable();
private static long[] initFactorialTable() {
    final long[] factorialTable = new long[21];
    factorialTable[0] = 1;
    for (int i=1; i<factorialTable.length; i++)
        factorialTable[i] = factorialTable[i-1] * i;
    return factorialTable;
}
/**
 * Actually, even for {@code long}, it works only until 20 inclusively.
 */
public static long factorial(final int n) {
    if ((n < 0) || (n > 20))
        throw new OutOfRangeException("n", 0, 20);
    return FACTORIAL_TABLE[n];
}

For the native type long(8 bytes), it can only hold up to 20!

对于本机类型long(8 个字节),它最多只能容纳20!

20! = 2432902008176640000(10) = 0x 21C3 677C 82B4 0000

Obviously, 21!will cause overflow.

显然,21!会造成溢出。

Therefore, for native type long, only a maximum of 20!is allowed, meaningful, and correct.

因此,对于 native type long,只20!允许最大值,有意义且正确。