I didn't find it, yet. Did I miss something? I know a factorial method is a common example programm for beginners. But wouldn't it be usefull to have a standard implementation for this one to reuse? I could use such a method with standard types (int, long...) and with BigInteger / BigDecimal, too.
我还没找到它。我错过了什么?我知道一个阶乘方法是初学者的常见示例程序。但是,重新使用这个标准实现是不是很有用?我可以使用标准类型(int,long ...)和BigInteger / BigDecimal这样的方法。
26 个解决方案
#1
25
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.
我不认为为factorial提供库函数会有用。对有效的因子实现进行了大量研究。这是一些实现。
#2
52
Apache Commons Math has a few factorial methods in the MathUtils class.
Apache Commons Math在MathUtils类中有一些因子方法。
#3
37
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;
}
#4
21
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)中,谷歌为“斯特林的近似”。
#5
10
Use Guava's BigIntegerMath
as follows:
使用Guava的BigIntegerMath如下:
BigInteger factorial = BigIntegerMath.factorial(n);
(Similar functionality for int
and long
is available in IntMath
and LongMath
respectively.)
(int和long的类似功能分别在IntMath和LongMath中可用。)
#6
6
Although factorials make a nice exercise for the beginning programmer, they're not very useful in most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.
虽然阶乘对于初级程序员来说是一个很好的练习,但在大多数情况下它们并不是很有用,而且每个人都知道如何编写阶乘函数,所以它们通常不在普通的库中。
#7
6
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!
对于本机类型长(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.
因此,对于原生类型长,最多只有20个!是允许的,有意义的和正确的。
#8
6
Because factorial grows so quickly, stack overflow is not an issue if you use recursion. In fact, the value of 20! is the largest one can represent in a Java long. So the following method will either calculate factorial(n) or throw an IllegalArgumentException if n is too big.
因为阶乘增长如此之快,如果使用递归,堆栈溢出不是问题。实际上,价值20!是Java中可以表示的最大长度。因此,如果n太大,以下方法将计算factorial(n)或抛出IllegalArgumentException。
public long factorial(int n) {
if (n > 20) throw new IllegalArgumentException(n + " is out of range");
return (1 > n) ? 1 : n * factorial(n - 1);
}
Another (cooler) way to do the same stuff is to use Java 8's stream library like this:
另一种(更酷)的方法是使用Java 8的流库,如下所示:
public long factorial(int n) {
if (n > 20) throw new IllegalArgumentException(n + " is out of range");
return LongStream.rangeClosed(1, n).reduce(1, (a, b) -> a * b);
}
Read more on Factorials using Java 8's streams
阅读使用Java 8流的Factorials的更多信息
#9
6
Apache Commons Math package has a factorial method, I think you could use that.
Apache Commons Math包有一个阶乘方法,我想你可以使用它。
#10
6
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);
}
}
#11
3
Try this
尝试这个
public static BigInteger factorial(int value){
if(value < 0){
throw new IllegalArgumentException("Value must be positive");
}
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= value; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
#12
2
I found an amazing trick to find factorials in just half the actual multiplications.
我找到了一个惊人的技巧,可以在实际乘法的一半中找到阶乘。
Please be patient as this is a little bit of a long post.
请耐心等待,因为这是一个很长的帖子。
For Even Numbers: To halve the multiplication with even numbers, you will end up with n/2 factors. The first factor will be the number you are taking the factorial of, then the next will be that number plus that number minus two. The next number will be the previous number plus the lasted added number minus two. You are done when the last number you added was two (i.e. 2). That probably didn't make much sense, so let me give you an example.
对于偶数:要将偶数乘以一半,最终会得到n / 2个因子。第一个因素将是您采用阶乘的数字,然后下一个因素是该数字加上该数字减去2。下一个数字将是前一个数字加上持续增加的数字减去两个。当您添加的最后一个号码为2(即2)时,您就完成了。这可能没有多大意义,所以让我举个例子。
8! = 8 * (8 + 6 = 14) * (14 + 4 = 18) * (18 + 2 = 20)
8! = 8 * 14 * 18 * 20 which is **40320**
Note that I started with 8, then the first number I added was 6, then 4, then 2, each number added being two less then the number added before it. This method is equivalent to multiplying the least numbers with the greatest numbers, just with less multiplication, like so:
请注意,我从8开始,然后我添加的第一个数字是6,然后是4,然后是2,每个数字加上比之前添加的数字少两个。此方法相当于将最小数字乘以最大数字,只需乘以较少的乘法,如下所示:
8! = 1 * 2 * 3 * 4 * 5 * 6 * 7 *
8! = (1 * 8) * (2 * 7) * (3 * 6) * (4 * 5)
8! = 8 * 14 * 18 * 20
Simple isn't it :)
简单不是吧:)
Now For Odd Numbers: If the number is odd, the adding is the same, as in you subtract two each time, but you stop at three. The number of factors however changes. If you divide the number by two, you will end up with some number ending in .5. The reason is that if we multiply the ends together, that we are left with the middle number. Basically, this can all be solved by solving for a number of factors equal to the number divided by two, rounded up. This probably didn't make much sense either to minds without a mathematical background, so let me do an example:
现在对于奇数:如果数字是奇数,则加法是相同的,就像你每次减去两个,但你停在三。然而,因素的数量会发生变化。如果将数字除以2,最终会得到一些以.5结尾的数字。原因是如果我们将两端相乘,那么我们就会留下中间的数字。基本上,这可以通过求解等于数除以2的多个因子来解决。对于没有数学背景的人来说,这可能没什么意义,所以让我举一个例子:
9! = 9 * (9 + 7 = 16) * (16 + 5 = 21) * (21 + 3 = 24) * (roundUp(9/2) = 5)
9! = 9 * 16 * 21 * 24 * 5 = **362880**
Note: If you don't like this method, you could also just take the factorial of the even number before the odd (eight in this case) and multiply it by the odd number (i.e. 9! = 8! * 9).
注意:如果你不喜欢这种方法,你也可以在奇数之前取偶数的阶乘(在这种情况下为8),然后乘以奇数(即9!= 8!* 9)。
Now let's implement it in Java:
现在让我们用Java实现它:
public static int getFactorial(int num)
{
int factorial=1;
int diffrennceFromActualNum=0;
int previousSum=num;
if(num==0) //Returning 1 as factorial if number is 0
return 1;
if(num%2==0)// Checking if Number is odd or even
{
while(num-diffrennceFromActualNum>=2)
{
if(!isFirst)
{
previousSum=previousSum+(num-diffrennceFromActualNum);
}
isFirst=false;
factorial*=previousSum;
diffrennceFromActualNum+=2;
}
}
else // In Odd Case (Number * getFactorial(Number-1))
{
factorial=num*getFactorial(num-1);
}
return factorial;
}
isFirst
is a boolean variable declared as static; it is used for the 1st case where we do not want to change the previous sum.
isFirst是一个声明为static的布尔变量;它用于我们不想改变之前的总和的第一种情况。
Try with even as well as for odd numbers.
尝试甚至和奇数一样。
#13
2
You can use recursion.
你可以使用递归。
public static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
and then after you create the method(function) above:
然后在创建上面的方法(函数)之后:
System.out.println(factorial(number of your choice));
//direct example
System.out.println(factorial(3));
#14
1
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.
对于类似的东西,很容易保留一个阶乘代码段或库函数。
#15
1
A very simple method to calculate factorials:
计算阶乘的一种非常简单的方法:
private double FACT(double n) {
double num = n;
double total = 1;
if(num != 0 | num != 1){
total = num;
}else if(num == 1 | num == 0){
total = 1;
}
double num2;
while(num > 1){
num2 = num - 1;
total = total * num2;
num = num - 1;
}
return total;
}
I have used double because they can hold massive numbers, but you can use any other type like int, long, float, etc.
我使用了double,因为它们可以容纳大量数字,但你可以使用任何其他类型,如int,long,float等。
P.S. This might not be the best solution but I am new to coding and it took me ages to find a simple code that could calculate factorials so I had to write the method myself but I am putting this on here so it helps other people like me.
附:这可能不是最好的解决方案,但我是编码的新手,我花了很多时间才找到一个可以计算阶乘的简单代码,所以我必须自己编写这个方法,但我把它放在这里,所以它有助于像我这样的其他人。
#16
1
You can use recursion version as well.
您也可以使用递归版本。
static int myFactorial(int i) {
if(i == 1)
return;
else
System.out.prinln(i * (myFactorial(--i)));
}
Recursion is usually less efficient because of having to push and pop recursions, so iteration is quicker. On the other hand, recursive versions use fewer or no local variables which is advantage.
由于必须推送和弹出递归,递归通常效率较低,因此迭代更快。另一方面,递归版本使用较少或没有局部变量,这是有利的。
#17
1
Factorial is highly increasing discrete function.So I think using BigInteger is better than using int. I have implemented following code for calculation of factorial of non-negative integers.I have used recursion in place of using a loop.
因子是高度增加的离散函数。所以我认为使用BigInteger比使用int更好。我已经实现了以下代码来计算非负整数的阶乘。我使用递归代替使用循环。
public BigInteger factorial(BigInteger x){
if(x.compareTo(new BigInteger("1"))==0||x.compareTo(new BigInteger("0"))==0)
return new BigInteger("1");
else return x.multiply(factorial(x.subtract(new BigInteger("1"))));
}
Here the range of big integer is
这里大整数的范围是
-2^Integer.MAX_VALUE (exclusive) to +2^Integer.MAX_VALUE,
where Integer.MAX_VALUE=2^31.
However the range of the factorial method given above can be extended up to twice by using unsigned BigInteger.
但是,通过使用无符号BigInteger,上面给出的阶乘方法的范围可以扩展到两倍。
#18
1
We have a single line to calculate it:
我们有一行来计算它:
Long factorialNumber = LongStream.rangeClosed(2, N).reduce(1, Math::multiplyExact);
#19
1
A fairly simple method
一个相当简单的方法
for ( int i = 1; i < n ; i++ )
{
answer = answer * i;
}
#20
1
/**
import java liberary class
*/
import java.util.Scanner;
/* class to find factorial of a number
*/
public class factorial
{
public static void main(String[] args)
{
// scanner method for read keayboard values
Scanner factor= new Scanner(System.in);
int n;
double total = 1;
double sum= 1;
System.out.println("\nPlease enter an integer: ");
n = factor.nextInt();
// evaluvate the integer is greater than zero and calculate factorial
if(n==0)
{
System.out.println(" Factorial of 0 is 1");
}
else if (n>0)
{
System.out.println("\nThe factorial of " + n + " is " );
System.out.print(n);
for(int i=1;i<n;i++)
{
do // do while loop for display each integer in the factorial
{
System.out.print("*"+(n-i) );
}
while ( n == 1);
total = total * i;
}
// calculate factorial
sum= total * n;
// display sum of factorial
System.out.println("\n\nThe "+ n +" Factorial is : "+" "+ sum);
}
// display invalid entry, if enter a value less than zero
else
{
System.out.println("\nInvalid entry!!");
}System.exit(0);
}
}
#21
0
public static int fact(int i){
if(i==0)
return 0;
if(i>1){
i = i * fact(--i);
}
return i;
}
#22
0
We need to implement iteratively. If we implement recursively, it will causes * if input becomes very big (i.e. 2 billions). And we need to use unbound size number such as BigInteger to avoid an arithmatic overflow when a factorial number becomes bigger than maximum number of a given type (i.e. 2 billion for int). You can use int for maximum 14 of factorial and long for maximum 20 of factorial before the overflow.
我们需要迭代实现。如果我们以递归方式实现,如果输入变得非常大(即20亿),它将导致*。并且我们需要使用未绑定的大小数字,例如BigInteger,以避免当因子数大于给定类型的最大数(即int为20亿)时的算术溢出。在溢出之前,您可以使用int最多14个阶乘和long最多20个阶乘。
public BigInteger getFactorialIteratively(BigInteger input) {
if (input.compareTo(BigInteger.ZERO) <= 0) {
throw new IllegalArgumentException("zero or negatives are not allowed");
}
BigInteger result = BigInteger.ONE;
for (BigInteger i = BigInteger.ONE; i.compareTo(input) <= 0; i = i.add(BigInteger.ONE)) {
result = result.multiply(i);
}
return result;
}
If you can't use BigInteger, add an error checking.
如果您无法使用BigInteger,请添加错误检查。
public long getFactorialIteratively(long input) {
if (input <= 0) {
throw new IllegalArgumentException("zero or negatives are not allowed");
} else if (input == 1) {
return 1;
}
long prev = 1;
long result = 0;
for (long i = 2; i <= input; i++) {
result = prev * i;
if (result / prev != i) { // check if result holds the definition of factorial
// arithmatic overflow, error out
throw new RuntimeException("value "+i+" is too big to calculate a factorial, prev:"+prev+", current:"+result);
}
prev = result;
}
return result;
}
#23
0
public int factorial(int num) {
if (num == 1) return 1;
return num * factorial(num - 1);
}
#24
0
while loop (for small numbers)
while循环(对于小数字)
public class factorial {
public static void main(String[] args) {
int counter=1, sum=1;
while (counter<=10) {
sum=sum*counter;
counter++;
}
System.out.println("Factorial of 10 is " +sum);
}
}
#25
0
I got this from EDX use it! its called recursion
我从EDX那里得到了它!它叫做递归
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n-1);
}
}
#26
0
with recursion:
递归:
public static int factorial(int n)
{
if(n == 1)
{
return 1;
}
return n * factorial(n-1);
}
with while loop:
with while循环:
public static int factorial1(int n)
{
int fact=1;
while(n>=1)
{
fact=fact*n;
n--;
}
return fact;
}
#1
25
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.
我不认为为factorial提供库函数会有用。对有效的因子实现进行了大量研究。这是一些实现。
#2
52
Apache Commons Math has a few factorial methods in the MathUtils class.
Apache Commons Math在MathUtils类中有一些因子方法。
#3
37
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;
}
#4
21
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)中,谷歌为“斯特林的近似”。
#5
10
Use Guava's BigIntegerMath
as follows:
使用Guava的BigIntegerMath如下:
BigInteger factorial = BigIntegerMath.factorial(n);
(Similar functionality for int
and long
is available in IntMath
and LongMath
respectively.)
(int和long的类似功能分别在IntMath和LongMath中可用。)
#6
6
Although factorials make a nice exercise for the beginning programmer, they're not very useful in most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.
虽然阶乘对于初级程序员来说是一个很好的练习,但在大多数情况下它们并不是很有用,而且每个人都知道如何编写阶乘函数,所以它们通常不在普通的库中。
#7
6
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!
对于本机类型长(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.
因此,对于原生类型长,最多只有20个!是允许的,有意义的和正确的。
#8
6
Because factorial grows so quickly, stack overflow is not an issue if you use recursion. In fact, the value of 20! is the largest one can represent in a Java long. So the following method will either calculate factorial(n) or throw an IllegalArgumentException if n is too big.
因为阶乘增长如此之快,如果使用递归,堆栈溢出不是问题。实际上,价值20!是Java中可以表示的最大长度。因此,如果n太大,以下方法将计算factorial(n)或抛出IllegalArgumentException。
public long factorial(int n) {
if (n > 20) throw new IllegalArgumentException(n + " is out of range");
return (1 > n) ? 1 : n * factorial(n - 1);
}
Another (cooler) way to do the same stuff is to use Java 8's stream library like this:
另一种(更酷)的方法是使用Java 8的流库,如下所示:
public long factorial(int n) {
if (n > 20) throw new IllegalArgumentException(n + " is out of range");
return LongStream.rangeClosed(1, n).reduce(1, (a, b) -> a * b);
}
Read more on Factorials using Java 8's streams
阅读使用Java 8流的Factorials的更多信息
#9
6
Apache Commons Math package has a factorial method, I think you could use that.
Apache Commons Math包有一个阶乘方法,我想你可以使用它。
#10
6
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);
}
}
#11
3
Try this
尝试这个
public static BigInteger factorial(int value){
if(value < 0){
throw new IllegalArgumentException("Value must be positive");
}
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= value; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
#12
2
I found an amazing trick to find factorials in just half the actual multiplications.
我找到了一个惊人的技巧,可以在实际乘法的一半中找到阶乘。
Please be patient as this is a little bit of a long post.
请耐心等待,因为这是一个很长的帖子。
For Even Numbers: To halve the multiplication with even numbers, you will end up with n/2 factors. The first factor will be the number you are taking the factorial of, then the next will be that number plus that number minus two. The next number will be the previous number plus the lasted added number minus two. You are done when the last number you added was two (i.e. 2). That probably didn't make much sense, so let me give you an example.
对于偶数:要将偶数乘以一半,最终会得到n / 2个因子。第一个因素将是您采用阶乘的数字,然后下一个因素是该数字加上该数字减去2。下一个数字将是前一个数字加上持续增加的数字减去两个。当您添加的最后一个号码为2(即2)时,您就完成了。这可能没有多大意义,所以让我举个例子。
8! = 8 * (8 + 6 = 14) * (14 + 4 = 18) * (18 + 2 = 20)
8! = 8 * 14 * 18 * 20 which is **40320**
Note that I started with 8, then the first number I added was 6, then 4, then 2, each number added being two less then the number added before it. This method is equivalent to multiplying the least numbers with the greatest numbers, just with less multiplication, like so:
请注意,我从8开始,然后我添加的第一个数字是6,然后是4,然后是2,每个数字加上比之前添加的数字少两个。此方法相当于将最小数字乘以最大数字,只需乘以较少的乘法,如下所示:
8! = 1 * 2 * 3 * 4 * 5 * 6 * 7 *
8! = (1 * 8) * (2 * 7) * (3 * 6) * (4 * 5)
8! = 8 * 14 * 18 * 20
Simple isn't it :)
简单不是吧:)
Now For Odd Numbers: If the number is odd, the adding is the same, as in you subtract two each time, but you stop at three. The number of factors however changes. If you divide the number by two, you will end up with some number ending in .5. The reason is that if we multiply the ends together, that we are left with the middle number. Basically, this can all be solved by solving for a number of factors equal to the number divided by two, rounded up. This probably didn't make much sense either to minds without a mathematical background, so let me do an example:
现在对于奇数:如果数字是奇数,则加法是相同的,就像你每次减去两个,但你停在三。然而,因素的数量会发生变化。如果将数字除以2,最终会得到一些以.5结尾的数字。原因是如果我们将两端相乘,那么我们就会留下中间的数字。基本上,这可以通过求解等于数除以2的多个因子来解决。对于没有数学背景的人来说,这可能没什么意义,所以让我举一个例子:
9! = 9 * (9 + 7 = 16) * (16 + 5 = 21) * (21 + 3 = 24) * (roundUp(9/2) = 5)
9! = 9 * 16 * 21 * 24 * 5 = **362880**
Note: If you don't like this method, you could also just take the factorial of the even number before the odd (eight in this case) and multiply it by the odd number (i.e. 9! = 8! * 9).
注意:如果你不喜欢这种方法,你也可以在奇数之前取偶数的阶乘(在这种情况下为8),然后乘以奇数(即9!= 8!* 9)。
Now let's implement it in Java:
现在让我们用Java实现它:
public static int getFactorial(int num)
{
int factorial=1;
int diffrennceFromActualNum=0;
int previousSum=num;
if(num==0) //Returning 1 as factorial if number is 0
return 1;
if(num%2==0)// Checking if Number is odd or even
{
while(num-diffrennceFromActualNum>=2)
{
if(!isFirst)
{
previousSum=previousSum+(num-diffrennceFromActualNum);
}
isFirst=false;
factorial*=previousSum;
diffrennceFromActualNum+=2;
}
}
else // In Odd Case (Number * getFactorial(Number-1))
{
factorial=num*getFactorial(num-1);
}
return factorial;
}
isFirst
is a boolean variable declared as static; it is used for the 1st case where we do not want to change the previous sum.
isFirst是一个声明为static的布尔变量;它用于我们不想改变之前的总和的第一种情况。
Try with even as well as for odd numbers.
尝试甚至和奇数一样。
#13
2
You can use recursion.
你可以使用递归。
public static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
and then after you create the method(function) above:
然后在创建上面的方法(函数)之后:
System.out.println(factorial(number of your choice));
//direct example
System.out.println(factorial(3));
#14
1
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.
对于类似的东西,很容易保留一个阶乘代码段或库函数。
#15
1
A very simple method to calculate factorials:
计算阶乘的一种非常简单的方法:
private double FACT(double n) {
double num = n;
double total = 1;
if(num != 0 | num != 1){
total = num;
}else if(num == 1 | num == 0){
total = 1;
}
double num2;
while(num > 1){
num2 = num - 1;
total = total * num2;
num = num - 1;
}
return total;
}
I have used double because they can hold massive numbers, but you can use any other type like int, long, float, etc.
我使用了double,因为它们可以容纳大量数字,但你可以使用任何其他类型,如int,long,float等。
P.S. This might not be the best solution but I am new to coding and it took me ages to find a simple code that could calculate factorials so I had to write the method myself but I am putting this on here so it helps other people like me.
附:这可能不是最好的解决方案,但我是编码的新手,我花了很多时间才找到一个可以计算阶乘的简单代码,所以我必须自己编写这个方法,但我把它放在这里,所以它有助于像我这样的其他人。
#16
1
You can use recursion version as well.
您也可以使用递归版本。
static int myFactorial(int i) {
if(i == 1)
return;
else
System.out.prinln(i * (myFactorial(--i)));
}
Recursion is usually less efficient because of having to push and pop recursions, so iteration is quicker. On the other hand, recursive versions use fewer or no local variables which is advantage.
由于必须推送和弹出递归,递归通常效率较低,因此迭代更快。另一方面,递归版本使用较少或没有局部变量,这是有利的。
#17
1
Factorial is highly increasing discrete function.So I think using BigInteger is better than using int. I have implemented following code for calculation of factorial of non-negative integers.I have used recursion in place of using a loop.
因子是高度增加的离散函数。所以我认为使用BigInteger比使用int更好。我已经实现了以下代码来计算非负整数的阶乘。我使用递归代替使用循环。
public BigInteger factorial(BigInteger x){
if(x.compareTo(new BigInteger("1"))==0||x.compareTo(new BigInteger("0"))==0)
return new BigInteger("1");
else return x.multiply(factorial(x.subtract(new BigInteger("1"))));
}
Here the range of big integer is
这里大整数的范围是
-2^Integer.MAX_VALUE (exclusive) to +2^Integer.MAX_VALUE,
where Integer.MAX_VALUE=2^31.
However the range of the factorial method given above can be extended up to twice by using unsigned BigInteger.
但是,通过使用无符号BigInteger,上面给出的阶乘方法的范围可以扩展到两倍。
#18
1
We have a single line to calculate it:
我们有一行来计算它:
Long factorialNumber = LongStream.rangeClosed(2, N).reduce(1, Math::multiplyExact);
#19
1
A fairly simple method
一个相当简单的方法
for ( int i = 1; i < n ; i++ )
{
answer = answer * i;
}
#20
1
/**
import java liberary class
*/
import java.util.Scanner;
/* class to find factorial of a number
*/
public class factorial
{
public static void main(String[] args)
{
// scanner method for read keayboard values
Scanner factor= new Scanner(System.in);
int n;
double total = 1;
double sum= 1;
System.out.println("\nPlease enter an integer: ");
n = factor.nextInt();
// evaluvate the integer is greater than zero and calculate factorial
if(n==0)
{
System.out.println(" Factorial of 0 is 1");
}
else if (n>0)
{
System.out.println("\nThe factorial of " + n + " is " );
System.out.print(n);
for(int i=1;i<n;i++)
{
do // do while loop for display each integer in the factorial
{
System.out.print("*"+(n-i) );
}
while ( n == 1);
total = total * i;
}
// calculate factorial
sum= total * n;
// display sum of factorial
System.out.println("\n\nThe "+ n +" Factorial is : "+" "+ sum);
}
// display invalid entry, if enter a value less than zero
else
{
System.out.println("\nInvalid entry!!");
}System.exit(0);
}
}
#21
0
public static int fact(int i){
if(i==0)
return 0;
if(i>1){
i = i * fact(--i);
}
return i;
}
#22
0
We need to implement iteratively. If we implement recursively, it will causes * if input becomes very big (i.e. 2 billions). And we need to use unbound size number such as BigInteger to avoid an arithmatic overflow when a factorial number becomes bigger than maximum number of a given type (i.e. 2 billion for int). You can use int for maximum 14 of factorial and long for maximum 20 of factorial before the overflow.
我们需要迭代实现。如果我们以递归方式实现,如果输入变得非常大(即20亿),它将导致*。并且我们需要使用未绑定的大小数字,例如BigInteger,以避免当因子数大于给定类型的最大数(即int为20亿)时的算术溢出。在溢出之前,您可以使用int最多14个阶乘和long最多20个阶乘。
public BigInteger getFactorialIteratively(BigInteger input) {
if (input.compareTo(BigInteger.ZERO) <= 0) {
throw new IllegalArgumentException("zero or negatives are not allowed");
}
BigInteger result = BigInteger.ONE;
for (BigInteger i = BigInteger.ONE; i.compareTo(input) <= 0; i = i.add(BigInteger.ONE)) {
result = result.multiply(i);
}
return result;
}
If you can't use BigInteger, add an error checking.
如果您无法使用BigInteger,请添加错误检查。
public long getFactorialIteratively(long input) {
if (input <= 0) {
throw new IllegalArgumentException("zero or negatives are not allowed");
} else if (input == 1) {
return 1;
}
long prev = 1;
long result = 0;
for (long i = 2; i <= input; i++) {
result = prev * i;
if (result / prev != i) { // check if result holds the definition of factorial
// arithmatic overflow, error out
throw new RuntimeException("value "+i+" is too big to calculate a factorial, prev:"+prev+", current:"+result);
}
prev = result;
}
return result;
}
#23
0
public int factorial(int num) {
if (num == 1) return 1;
return num * factorial(num - 1);
}
#24
0
while loop (for small numbers)
while循环(对于小数字)
public class factorial {
public static void main(String[] args) {
int counter=1, sum=1;
while (counter<=10) {
sum=sum*counter;
counter++;
}
System.out.println("Factorial of 10 is " +sum);
}
}
#25
0
I got this from EDX use it! its called recursion
我从EDX那里得到了它!它叫做递归
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n-1);
}
}
#26
0
with recursion:
递归:
public static int factorial(int n)
{
if(n == 1)
{
return 1;
}
return n * factorial(n-1);
}
with while loop:
with while循环:
public static int factorial1(int n)
{
int fact=1;
while(n>=1)
{
fact=fact*n;
n--;
}
return fact;
}