现在的位置: 首页 > 语言拓展 > 正文

高精度阶乘的计算

2011年03月23日 语言拓展 ⁄ 共 27字 ⁄ 字号 暂无评论

能够得到正确结果的程序

下面的程序可以计算出 n 的阶乘(n<=12)

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
int main()
{
    int i, n, product;
    product = 1;
    scanf("%d", &n);
    for (i=2; i<=n; i++)
        product = product * i;
    printf("%d\n", product);
    return 0;
}

12的阶乘是 479001600。int能够表示的范围是 21亿,而13的阶乘超过了这个范围。

如果 n 很大,就要采用下面的方法了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
 
#define SIZE 5000
 
int main(int argc, char *argv[])
{
	int i, j, c, n;
	int f[SIZE];
 
	scanf("%d", &n);
 
	for (i=0; i<SIZE; i++) 
		f[i] = 0;
 
	f[0] = 1; /* n=1 */
 
	for(i=2; i<=n; i++) {
		c = 0;
		for (j=0; j<SIZE; j++) {
			c = f[j] * i + c;
			f[j] = c % 10;
			c = c / 10;
		}
	}
 
	/* Print out the result */
	i = SIZE;
	while (f[--i]==0);
	while (i>=0) printf("%d", f[i--]);
 
	return 0;
}

使用JAVA编写计算n的阶乘,就非常简单,这全拜面向对象编程的威力!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.math.BigInteger;
import java.util.Scanner;
 
public class P354 {
    public static void main(String[] args) {
        int i, n;
        Scanner cin = new Scanner(System.in);
        n = cin.nextInt();
        BigInteger product = new BigInteger("1");
        for (i = 1; i <= n; i++) 
            product = product.multiply(new BigInteger(String.valueOf(i)));
        System.out.println(product);
    }
}

抱歉!评论已关闭.