`
ethen
  • 浏览: 119679 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

大数的阶乘

阅读更多

大数的阶乘,没想到啥好办法,姑且如此吧。

import java.math.BigInteger;

public class Factorials {
	static int index = 1;

	public static void main(String args[]) {
		long starttime = System.currentTimeMillis();
		
		int num[] = new int[10000];
		num[0] = 1;
		int n = Integer.parseInt(args[0]);
		for (int i = 1; i < n; i++) {
			int j = 0;
			int carry = 0;
			while (j < index) {
				num[j] *= i;
				num[j] += carry;
				carry = (num[j] / 10000);
				num[j] = (num[j] % 10000);
				j++;
			}
			if (carry > 0) {
				index = j + 1;
				num[j] = carry;
			}
		}

		for (int i = index - 1; i >= 0; i--) {
			String s = "";
			if (num[i] == 0)
				s = "0000";
			else if (num[i] < 10)
				s = "000" + num[i];
			else if (num[i] < 100)
				s = "00" + num[i];
			else if (num[i] < 1000)
				s = "0" + num[i];
			else
				s = "" + num[i];
			System.out.print(s);
		}
		System.out.println();
		long endtime = System.currentTimeMillis();
		System.out.println((endtime - starttime) + "(ms)");
		
		starttime = System.currentTimeMillis();
		BigInteger b = new BigInteger("1");
		for (int i = 1; i < n; i++) {
			BigInteger c = new BigInteger("" + i + "");
			b = b.multiply(c);
		}
		System.out.println(b);
		endtime = System.currentTimeMillis();
		System.out.println((endtime - starttime) + "(ms)");
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics