您的位置:首页 > 编程语言 > Java开发

java-用数组实现大数阶乘

2016-09-27 10:15 357 查看
import java.util.Scanner;

class Factorial {
void Carry(int[] array, int pos) {
int i, carry = 0;
for (i = 0; i <= pos; i++) {// 从0到pos检查是否需要进位
array[i] += carry;// 累加进位
if (array[i] < 10) {// 小于10不进位
carry = 0;
} else if (array[i] > 9 && i < pos) {// 大于9,但不是最高位
carry = array[i] / 10;
array[i] = array[i] % 10;
} else {// 大于9,且是最高位
while (array[i] > 9) {// 循环向前进位
carry = array[i] / 10;// 计算进位值
array[i] = array[i] % 10;
i++;
array[i] = carry;// 在下一位保存进位值
}

}
}
}

void bigFactorial(int number) {
int pos = 0;// 最高位记录点
int length;// 数据长度
int i, j;
int m = 0, n = 0;// 统计输出位数和行数
double sum = 0;// 阶乘位数

for (i = 1; i <= number; i++) {// 计算阶乘位数
sum += Math.log10(i);
}
length = (int) sum + 1;// 数据长度

int[] array = new int[length];// 初始化一个数组
array[0] = 1;

for (i = 2; i <= number; i++) {
for (j = length - 1; j >= 0; j--) {// 查找最高位
if (array[j] != 0) {
pos = j;// 记录最高位
break;
}
}

for (j = 0; j <= pos; j++) {
array[j] *= i;
}
Carry(array, pos);
}

for (j = length - 1; j >= 0; j--) {
if (array[j] != 0) {
pos = j;
break;
}
}

System.out.println(number + "的阶乘为:");
for (i = pos; i >= 0; i--) {
System.out.print(array[i]);
m++;
if (m % 5 == 0) {
System.out.print(" ");
}
if (m == 40) {
System.out.println("");
m = 0;
n++;
if (n == 10) {
System.out.println("");
n = 0;
}
}
}
System.out.println("\n" + "阶乘共有:" + (pos + 1) + "位");
}

public void doBigFactorial(int number) {
int timeBegin = (int) System.currentTimeMillis();
bigFactorial(number);
int timeFinish = (int) System.currentTimeMillis();
int time = timeFinish - timeBegin;
System.out.println("计算耗时:" + time + "毫秒");
}

public static void main(String[] args) {
Factorial fac = new Factorial();
Scanner in = new Scanner(System.in);
System.out.println("请输入阶乘的数:");
int num = in.nextInt();
fac.doBigFactorial(num);
}

}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: