P1009 Valley and Los solution to a problem of factorial

Click here to see the original title: Portal

Look at the original question:

Description Title 
High Precision calculated S = . 1 +! 2 +! 3 + ... + n-(N ≤!! 50 ) 

wherein represents a factorial, such as "!": 5 ! = 5 * 4 * 3 * 2 * 1 5 ! = . 5 × . 4 × . 3 × 2 × . 1 . 

Input format 
a positive integer N. 

Output Format 
a positive integer S, represents the calculation results. 

Sample Input Output 
Input 
3 
Output 
9

If this question does not require a highly accurate, then it becomes very easy, but because we see the valley of Los labeled "high-precision" label but because This question is factorial and therefore more back n factorial it will be.

And because n! = n * (n-1 !, so there is transfer equation n! = n * (n- 1)! to avoid duplication of operations (ROS just a nagging prevent some people do not know forget this method)

Precision is also very common, but ROS for a long time because this question debug '+ =' written '='

So a place to write code is wrong it will be a variety metaphysics bug

code show as below:

 1 #include<bits/stdc++.h>
 2 #define N 1000000
 3 using namespace std;
 4 int n;
 5 int tmp[N];
 6 int lt;
 7 int a[N];
 8 int la;
 9 int lm;
10 void cal(int);
11 int main(){
12     scanf("%d",&n);
13     tmp[1]=1;
14     lt=1;
15     for(int i=1;i<=n;i++){
16         cal(i);
17         lm=max(lt,la);
18         for(int j=1;j<=lm;j++){
19             a[j]+=tmp[j];
20         }
21         for(int j=1;j<=lm;j++){
22             a[j+1]+=a[j]/10;
23             a[j]%=10;
24         }
25         la=lm;
26         while(a[la+1]>0){
27             la++;
28             a[la+1]+=a[la]/10;
29             a[la]%=10;
30         }
31     }
32     for(int i=la;i>2;i--){
33         if(a[i]==0){
34             la--;
35             continue;
36         }
37         break;
38     }
39     for(int i=la;i>=1;i--){
40         printf("%d",a[i]);
41     }
42     return 0;
43 }
44 void cal(int x){
45     for(int i=1;i<=lt;i++){
46         tmp[i]*=x;
47     }
48     for(int i=1;i<=lt;i++){
49         if(tmp[i]>=10){
50             tmp[i+1]+=tmp[i]/10;
51             tmp[i]%=10;
52         }
53     }
54     while(tmp[lt+1]>0){
55         lt++;
56         tmp[lt+1]+=tmp[lt]/10;
57         tmp[lt]%=10;
58     }
59     return ;
60 }

 

Guess you like

Origin www.cnblogs.com/robertspot/p/12370027.html