PAT 基礎編程題目集 6-10 階乘計算升級版 (20 分)


本題要求實現一個打印非負整數階乘的函數。

函數接口定義:

void Print_Factorial ( const int N );

其中N是用戶傳入的參數,其值不超過1000。如果N是非負整數,則該函數必須在一行中打印出N!的值,否則打印“Invalid input”。

裁判測試程序樣例:

#include <stdio.h>

void Print_Factorial ( const int N );

int main()
{
    int N;
	
    scanf("%d", &N);
    Print_Factorial(N);
    return 0;
}

/* 你的代碼將被嵌在這里 */

輸入樣例:

15

輸出樣例:

1307674368000

現學現賣,敲一遍高精度階乘
 1 #include <stdio.h>
 2 void Print_Factorial ( const int N );
 3 int main()
 4 {
 5     int N;
 6     
 7     scanf("%d", &N);
 8     Print_Factorial(N);
 9     return 0;
10 }
11 void Print_Factorial ( const int N )
12 {
13     if(N<0){
14         printf("Invalid input\n");
15         return ;
16     }
17     int d[40000];
18     d[0]=1;
19     int t=0,tmp=0,carry=0;
20     for(int i=1;i<=N;i++){
21         for(int j=0;j<=t;j++){
22             tmp=d[j]*i+carry;
23             d[j]=tmp%10;
24             carry=tmp/10;
25         }
26         while(carry!=0){
27             d[++t]=carry%10;
28             carry/=10;
29         }
30     }
31     for(int i=t;i>=0;i--){
32         printf("%d",d[i]);
33     }
34     printf("\n");
35 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM