閱讀163 返回首頁    go 阿裏雲 go 技術社區[雲棲]


大數的階乘算法

#include <stdio.h>

#define MAX_LENGTH 20000

// 大數階乘算法
int main()
{
	int i, j, temp;
	int bitSize = 1;  // 結果的位數
	int result[MAX_LENGTH];
	int n = 0; // 求n的階乘
	int carryBit = 0;

	scanf("%d", &n);
    result[0] = 1;

	for (i = 2; i <= n; i++)
	{
		carryBit = 0; // 進位位

		// 每次都是將當前結果從低位到高位依次與i相乘
		for (j = 1; j <= bitSize; j++) 
		{
			temp = result[j - 1] * i + carryBit;
			result[j - 1] = temp % 10; 
			carryBit = temp / 10;
		}

		while (carryBit != 0)
		{
			result[bitSize++] = carryBit % 10;
			carryBit /= 10;
		}
	}

	// 結果是倒序的,所以要倒著輸出
	for (i = bitSize - 1; i >= 0; i--)
	{
		printf("%d", result[i]);
	}
	putchar(10);

	return 0;
}

最後更新:2017-04-03 18:52:03

  上一篇:go 堅持編程:如何找到一份工程師工作
  下一篇:go telerik安裝教程