# Java 小例子：大数乘法和阶乘

30 篇文章 0 订阅

public class BigMultiply {

public static void main(String[] args) {
System.out.println(factorial("1000"));
}

/**
* 阶乘
*
* @param n 要进行阶乘的数字
*
* @return 阶乘结果
*/
private static String factorial(String n) {
if (Integer.parseInt(n) <= 1) {
return "1";
} else {
return bigMultiply(n, factorial(String.valueOf(Integer.parseInt(n) - 1)));
}
}

/**
* 大数字乘法
*
* @param number1 数字1
* @param number2 数字2
*
* @return 乘法结果
*/
private static String bigMultiply(String number1, String number2) {
short[] numbers1 = toIntArray(number1);
short[] numbers2 = toIntArray(number2);

short[] result = multiply(numbers1, numbers2);
}

private static short[] multiply(short[] numbers1, short[] numbers2) {
short[] result = new short[numbers1.length + numbers2.length];

for (int i = 0; i < numbers1.length; i++) {
for (int j = 0; j < numbers2.length; j++) {
int tenth = i + j;
int cellResult = numbers1[i] * numbers2[j];

put(result, tenth + 1, cellResult % 10);
put(result, tenth, cellResult / 10);
}
}

return result;
}

/**
* put <i>number</i> into <i>index</i> position of <i>result</i>
*
* @param result -
* @param index  -
* @param number -
*/
private static void put(short[] result, int index, int number) {
result[index] += number;

carryFrom(result, index);
}

/**
* 进位
*
* @param result 数组
* @param index  开始进位的位置
*/
private static void carryFrom(short[] result, int index) {
if (index < 0) {
return;
}

if (result[index] >= 10) {
result[index - 1]++;
result[index] = (short)(result[index] - 10);
carryFrom(result, index - 1);
}
}

private static short[] toIntArray(String numbers) {
short[] result = new short[numbers.length()];
for (int i = 0; i < numbers.length(); i++) {
result[i] = (short)(Integer.parseInt(numbers.substring(i, i + 1)));
}
return result;
}

private static String toString(short[] ints) {
int start = 0;
while (ints[start] == 0) {
start++;
}

String str = "";
while (start < ints.length) {
str += ints[start];
start++;
}

return str;
}
}

01-25
04-11 501

08-27 4490
02-28 505
09-01 3万+
09-11 308
08-17 270
04-16 3635
03-18 522
08-15 2641
06-24 1071
12-20 4743
09-14 604
06-07 1966
03-07 909
06-01 6274
03-04 1万+
03-09 1万+
04-15 1万+

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。