1. 程式人生 > >java-用陣列實現大數階乘

java-用陣列實現大數階乘

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);
	}

}