-
Notifications
You must be signed in to change notification settings - Fork 0
/
factor.cpp
91 lines (80 loc) · 1.57 KB
/
factor.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
*大数阶乘算法
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
#define MAX 10000
int fac[MAX]={1,};
int add[MAX]={0,};
int top=1;//计算结果位数
void calculate(int n);
void print();
int main(int argc, char * argv[])
{
int n;
cout<<"please input the number:";
while (cin >> n && n > 0) {
calculate(n);
cout<<n<<"!=";
print();
cout<<"总共"<<top<<"位"<<endl;
cout<<"please input the number:";
}
return 0;
}
//计算N的阶乘
void calculate(int n)
{
memset(fac, 0, sizeof(fac));
memset(add, 0, sizeof(add));
fac[0] = 1;
top = 1;
if (n<=0)
{
exit(1);
}
for (int i=1;i<=n;i++)
{
int m=top;
for (int j=0;j<m;j++)
{
int tmp=fac[j]*i;
if (j==0)
{
fac[0]=tmp%10;
add[0]=tmp/10;
}
else
{
fac[j]=(tmp+add[j-1])%10;
add[j]=(tmp+add[j-1])/10;
}
/**最高位有进位
**连续进位的问题
*/
while (add[top-1]>0){
top++;
int tmp=fac[top-1];
fac[top-1]=(tmp+add[top-2])%10;
add[top-1]=(tmp+add[top-2])/10;
}
}
}
}
//打印输出结果
void print()
{
int j=0;
for(int i=top-1;i>=0;i--)
{
if ((j++)%20==0)
{
cout<<endl;
}
cout<<fac[i];
}
cout<<endl;
}