生活随笔
收集整理的這篇文章主要介紹了
算法:高精度阶乘
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
? ?問題描述:
????????輸入一個正整數(shù)n,輸出n!的值,這里的階乘結(jié)果必須是完全準確的,每一位都需要被精確輸出,而且這里的計算結(jié)果有可能會非常巨大,超過計算機中的任何數(shù)據(jù)類型。
????????階乘的計算公式:n!=1*2*3*…*n。
??????解題思路:
????????對于高精度要求的計算,我們一般的思路是如何準確拆解并分析每一個最小元素,如何精確保存每一位元素,最終又如果把它們?nèi)嗪铣梢粋€整體。
????????對于這一個問題,我們的首要思路是:
????????????1.?把最大元素拿來做每位拆分,并存儲進數(shù)組中。
????????????2.?把每一次的乘數(shù)都和數(shù)組中的有效位分別相乘,然后統(tǒng)一進位處理。
????????????3.?最后從數(shù)組首位開始尋找,直到找到第一位真正有效的輸出數(shù)據(jù)(!=0?&&?!=-1),依次輸出。
??????下面是這個問題的參考代碼,代碼中對于必要的步驟進行了相應的注釋:
????????參考代碼:
1 #include<stdio.h>
2
3 void BitMul(
int* result,
int top,
int num);
4 int main(){
5 int n,top=
10000;
6 int result[top];
7 scanf(
"%d",&
n);
8 if(n==
0)
9 {
10 printf(
"0");
11 return 0;
12 }
13
14 int i=
0,temp;
15 for(i=
0;i<top;i++
)
16 result[i]=-
1;
//初始化每位標志-1
17 int temp_num=n,temp_id=
top;
18 while(temp_num)
//正向拆分每一位
19 {
20 temp_id--
;
21 result[temp_id]=temp_num%
10;
22 temp_num/=
10;
23 }
24
25 if(n>
1)
26 {
27 while(n-
1>
1)
//這里注意因為已經(jīng)利用最大數(shù)進行了初始化。
28 {
//所以從n-1開始計算
29 BitMul(result,top,n-
1);
30 n--
;
31 }
32 }
33
34 for(i=
0;result[i]==-
1||result[i]==
0;i++);
//進入真正的第一個非零位
35 for(;i<top;i++
)
36 printf(
"%d",result[i]);
//從第一位非零位開始真正輸出
37 return 0;
38 }
39
40 void BitMul(
int* result,
int top,
int num){
41 int temp_top=top-
1;
//指向數(shù)組內(nèi)存上界的真實地址
42 while(result[temp_top]!=-
1)
43 {
44 result[temp_top]*=num;
//每一位與數(shù)字相乘,不要著急進位
45 temp_top--
;
46 }
47 temp_top=top-
1;
48 while(result[temp_top]!=-
1)
49 {
50 if(result[temp_top]>
9)
//根據(jù)不同情況依次進位
51 {
52 if(result[temp_top-
1]==-
1)
//如果前一位為-1,代表沒有任何操作過
53 result[temp_top-
1]=result[temp_top]/
10;
54 else
55 result[temp_top-
1]+=(result[temp_top]/
10);
56 result[temp_top]%=
10;
57 }
58 temp_top--
;
59 }
60 }
?
轉(zhuǎn)載于:https://www.cnblogs.com/corerman/p/4726922.html
總結(jié)
以上是生活随笔為你收集整理的算法:高精度阶乘的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。