Problem Description:
Enter a positive integer n, output the value of n!, where the factorial result must be completely accurate, each bit needs to be precisely output, and the results here can be very large, more than any data type on the computer.
Calculation formula for factorial: N!=1*2*3*...*n.
Problem Solving Ideas:
For the calculation of high-precision requirements, our general idea is how to accurately disassemble and analyze each of the smallest elements, how to accurately save each element, and eventually if they are kneaded into a whole.
For this question, our first thought is:
1. Take the maximum element for each split and store it in the array.
2. Multiply each multiplier by a valid bit in the array, and then carry it uniformly.
3. Finally start with the array first, until we find the first truly valid output data (!=0 &&!=-1), then output.
The following is the reference code for this question, which is commented out in the code for the necessary steps:
Reference code:
1#include <stdio.h>2 3 voidBitmul (int* result,intTopintnum);4 intMain () {5 intn,top=10000;6 intResult[top];7scanf"%d",&n);8 if(n==0)9 {Tenprintf"0"); One return 0; A } - - intI=0, temp; the for(i=0; i<top;i++) -result[i]=-1;//initialize each bit of flag -1 - intTemp_num=n,temp_id=top; - while(Temp_num)//splitting each bit forward + { -temp_id--; +result[temp_id]=temp_num%Ten; ATemp_num/=Ten; at } - - if(n>1) - { - while(n1>1)//note here because the maximum number has been initialized. -{//so, starting from N-1 , inBitmul (result,top,n-1); -n--; to } + } - the for(i=0; result[i]==-1|| result[i]==0; i++);//into the real first non-0-bit * for(; i<top;i++) $printf"%d", Result[i]);//true output starting from the first non-0 bitPanax Notoginseng return 0; - } the + voidBitmul (int* result,intTopintnum) { A inttemp_top=top-1;//real address to upper bound of array memory the while(result[temp_top]!=-1) + { -Result[temp_top]*=num;//each one multiplied by the number, do not rush to carry $temp_top--; $ } -temp_top=top-1; - while(result[temp_top]!=-1) the { - if(result[temp_top]>9)//Carry in order according to different circumstancesWuyi { the if(result[temp_top-1]==-1)//if the previous digit is-1, the delegate has no action -result[temp_top-1]=result[temp_top]/Ten; Wu Else -result[temp_top-1]+= (result[temp_top]/Ten); Aboutresult[temp_top]%=Ten; $ } -temp_top--; - } -}
Algorithm: high-precision factorial