ITeye博客

数组法求30的阶乘

fish8077 · 2011-02-23 10:25 · java · 编程语言 · Markdown



public class Test {
	public static void main(String[] args) {
		int[] sum = new int[50]; // 用来保存值
		sum[1] = 1; //个位数为1(初始值)
		int w = 1; // 位数
		// 求30的阶乘
		for (int i = 1; i <= 30; i++) {
			// 每一位都要乘上当前的阶乘
			for (int j = 1; j <= w; j++) {
				sum[j]*=i;
			}
			// 进位
			for (int j = 1; j <= w; j++) {
				// 如果是最高位,判断是否要进位
				if (j == w) {
					if (sum[j]>10) {
						w++; // 位数要加1
						sum[j+1] += sum[j]/10;
						sum[j]%=10;
					}
				} else {
					sum[j+1] += sum[j]/10;
					sum[j]%=10;
				}
			}
			// 打印
			System.out.println(i+"的阶乘为:");
			for (int j = w; j >= 1; j--) {
				System.out.print(sum[j]);
			}
			System.out.println();
		}
	}
}


评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。