大正整数乘法(非BigInteger)及几种阶乘算法
1,2个大整数相乘:
String bignumMult(String num1,String num2){
int
[] b1
=
fromStr2IntArray(num1);
if
(b1
==
null
||
b1.length
==
0
){
return
null
;
}
int
[] b2
=
fromStr2IntArray(num2);
if
(b2
==
null
||
b2.length
==
0
){
return
null
;
}
//
outBytes的最大长度不会超过b1.length+b2.length+1
int
[] outBytes
=
new
int
[b1.length
+
b2.length
+
1
];
for
(
int
i
=
0
; i
<
b1.length; i
++
){
for
(
int
j
=
0
; j
<
b2.length; j
++
){
int
index
=
i
+
j;
//
暂时不进位
outBytes[index]
=
outBytes[index]
+
b1[i]
*
b2[j];
}
}
for
(
int
i
=
0
; i
<
outBytes.length; i
++
){
int
r
=
outBytes[i];
if
(r
>=
10
){
outBytes[i]
=
r
%
10
;
outBytes[i
+
1
]
=
r
/
10
+
outBytes[i
+
1
];
}
}
StringBuilder sb
=
new
StringBuilder(
“”
);
int
begin
=
–
1
;
for
(
int
i
=
outBytes.length
–
1
; i
>=
0
; i
—
){
if
(outBytes[i]
!=
0
){
begin
=
i;
break
;
}
}
if
(begin
==
–
1
){
return
“
0
“
;
}
for
(
int
i
=
begin; i
>=
0
; i
—
){
sb.append(outBytes[i]);
}
return
sb.toString();
}
int
[] fromStr2IntArray(String src){
if
(src
==
null
||
src.trim().equals(
“”
)){
return
null
;
}
int
len
=
src.length();
int
[]rt
=
new
int
[len];
for
(
int
i
=
0
; i
<
len; i
++
){
int
tmp
=
src.charAt(len
–
1
–
i)
–
48
;
if
(tmp
<
0
||
tmp
>=
10
){
return
null
;
}
rt[i]
=
tmp;
}
return
rt;
}
2,阶乘算法一:
String sp(
int
n) {
if
(n
<=
1
) {
return
“
1
“
;
}
String result
=
“
1
“
;
for
(
int
i
=
1
; i
<=
n; i
++
){
result
=
new
BigInteger(result).multiply(BigInteger.valueOf(i)).toString();
}
return
result;
}
3,阶乘算法二:
String sp1(
int
n){
if
(n
<=
1
) {
return
“
1
“
;
}
String result
=
“
1
“
;
for
(
int
i
=
1
; i
<=
n; i
++
){
result
=
bignumMult(result,Integer.toString(i));
}
return
result;
}
4,阶乘算法三:
void
sp2(
int
n){
int
size
=
1000000
;
int
[] bigArray
=
new
int
[size];
bigArray[
0
]
=
1
;
for
(
int
i
=
1
; i
<
size; i
++
) {
bigArray[i]
=
–
1
;
}
int
tempCount
=
0
;
int
k1;
for
(
int
i
=
n; i
>
0
; i
—
) {
for
(
int
j
=
0
; j
<
size; j
++
) {
if
(bigArray[j]
==
–
1
) {
k1
=
j;
//
向高位进位
while
(tempCount
>
0
) {
bigArray[k1]
=
tempCount
%
10
;
tempCount
=
tempCount
/
10
;
k1
++
;
}
break
;
}
int
tempMul
=
bigArray[j]
*
i;
tempCount
=
tempCount
+
tempMul;
bigArray[j]
=
tempCount
%
10
;
tempCount
=
tempCount
/
10
;
}
}
int
i
=
size
–
1
;
while
(i
>=
0
) {
if
(bigArray[i]
!=
–
1
) {
System.out.print(bigArray[i]);
}
i
—
;
}
}