package
com.zf.s2;
import
java.math.BigInteger;
import
java.util.ArrayList;
import
java.util.List;
public
class
TextFactorial {
public
static
int
simpleCircle(
int
num){
int
sum=
1
;
if
(num<
0
){
throw
new
IllegalArgumentException(
"必须为正整数!"
);
}
for
(
int
i=
1
;i<=num;i++){
sum *= i;
}
return
sum;
}
public
static
int
recursion(
int
num){
int
sum=
1
;
if
(num <
0
)
throw
new
IllegalArgumentException(
"必须为正整数!"
);
if
(num==
1
){
return
1
;
}
else
{
sum=num * recursion(num-
1
);
return
sum;
}
}
public
static
long
addArray(
int
num){
long
[]arr=
new
long
[
21
];
arr[
0
]=
1
;
int
last=
0
;
if
(num>=arr.length){
throw
new
IllegalArgumentException(
"传入的值太大"
);
}
if
(num <
0
)
throw
new
IllegalArgumentException(
"必须为正整数!"
);
while
(last<num){
arr[last+
1
]=arr[last]*(last+
1
);
last++;
}
return
arr[num];
}
public
static
synchronized
BigInteger bigNumber(
int
num){
ArrayList list =
new
ArrayList();
list.add(BigInteger.valueOf(
1
));
for
(
int
i = list.size(); i <= num; i++) {
BigInteger lastfact = (BigInteger) list.get(i -
1
);
BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(i));
list.add(nextfact);
}
return
(BigInteger) list.get(num);
}
public
static
void
main(String []args){
int
num=
5
;
int
num1=
23
;
System.out.println(
"简单的循环计算"
+num+
"的阶乘为"
+simpleCircle(num));
System.out.println(
"利用递归计算"
+num+
"的阶乘为"
+recursion(num));
System.out.println(
"数组添加计算"
+num+
"的阶乘为"
+addArray(num));
System.out.println(
"利用BigInteger类计算"
+num1+
"的阶乘为"
+bigNumber(num1));
}
}