CodeGym /Java 博客 /随机的 /阶乘的Java程序
John Squirrels

San Francisco

# 阶乘的Java程序

1！= 1 2！= 1 * 2 = 2 3！= 1 * 2 * 3 = 6 4！= 1 * 2 * 3 * 4 = 24 5！= 1 * 2 * 3 * 4 * 5 = 120

!0 = 1

6！-4！= 1·2·3·4·5·6 - 1·2·3·4 = 720 - 24 = 696

## 阶乘程序中的普通解

``````
class FactorialExample{
public static void main(String args[]){
int i,fact=1;
int number=7;// our number to do the necessary calculations in class Factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
``````

7 的阶乘是：5040

``````
public static int getFactorial(int f) {
int result = 1;
for (int i = 1; i <= f; i++) {
result = result * i; // finding factorial of number using loops
}
return result;
}
``````

``````
System.out.println(getFactorial(6) - getFactorial(4));
``````

## 递归求解

1. 终止条件——当满足终止条件时，该方法应停止调用自身并开始向上传递值。毕竟，如果没有终止条件，那么我们将有一个无限循环，方法会反复调用自身，直到我们得到StackOverflowError
2. 无论情况需要什么逻辑加上递归调用，但具有不同的输入值。

``````
public static int getFactorial(int f) { // finding factorial of number using recursive solution
if (f <= 1) {
return 1;
}
else {
return f * getFactorial(f - 1);
}
}
``````

## 流解决方案

``````
public static int getFactorial(int f) { // finding factorial of number using Stream
if (f <= 1) {
return 1;
}
else {
return IntStream.rangeClosed(2, f).reduce((x, y) -> x * y).getAsInt();
}
}
``````

## 普通溶液

``````
public static BigInteger getFactorial(int f) { // finding factorial of number using BigInteger
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= f; i++)
result = result.multiply(BigInteger.valueOf(i));
return result;
}
``````

## 递归求解

``````
public static BigInteger getFactorial(int f) {
if (f <= 1) {
return BigInteger.valueOf(1);
}
else {
return BigInteger.valueOf(f).multiply(getFactorial(f - 1));
}
}
``````

## 流解决方案

``````
public static BigInteger getFactorial(int f) {
if (f < 2) {
return BigInteger.valueOf(1);
}
else {
return IntStream.rangeClosed(2, f).mapToObj(BigInteger::valueOf).reduce(BigInteger::multiply).get();
}
}
``````

9332621544394415268169923885626670049071596826438162146859296389521759999322991560894146397615651828625369792082722375825 1185210916864000000000000000000000000

TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION