网站建议:179001057@qq.com

求算大数(比如100)阶乘的思路

技术2022-05-11  0

求算大数(比如100)阶乘的思路

/*   可以把n!的结果放在数组中,数组中每个元素都表示n!值的一位.   对整数范围内的n,求n!.   对于输入的n想办法昼精确地估计出n!所占的位数.就能确定数组元素的个数   可以将n!表示成10的次幂,即n!=10^M(10的M次方)则不小于M的最小整数就是   n!的位数,对该式两边取对数,有=log10^n!即:   M = log10^1+log10^2+log10^3...+log10^n   循环求和,就能算得M值,该M是n!的精确位数。   数组初始化时,令数组第一个元素(n!的第一位)为整数1,其余为0.   在数组中计算n!时是通过将数组中的值乘2,3,4,。。一直到乘n的方式得的   把数组的第一个元素看做是n!的最低位,最后一个元素看做是最高位。   */#include <iostream>;using namespace std;#include <cmath>;#include <cstdlib>;#include <iomanip>;int getN(); //输入nint getBitNum(int n); //求n!的位数char *init(int size);void calc(char *a,int n); //求n!void display(char *a,int size);int main(){    int n = getN();    int size = getBitNum(n);    char *pa = init(size);    calc(pa,n);    display(pa,size);    delete []pa; //note:}int getN(){    int n;    cout << "Please input n of n! : ";    cin >;>; n;    while(n < 0) {        cout << "input error,again: ";        cin >;>; n;    }    if(n == 0)        exit(1);    return n;}int getBitNum(int n){    double sum = 1.0;    for(int i=1; i<=n; i++)        sum += log10((long double)i); //参数为double &和long double&                                      //不转换重载函数不能解析    return int(sum); //不转换会有warning}char * init(int size){    char *pa = new char[size];    if(!pa) { //n太大时考虑申请内存不成功情况的执行动作        cout << "too large factor of " << size << endl;        exit(1);    }    pa[0] = 1;    for(int i=1; i<size; i++)        pa[i] = 0;    return pa;}void calc(char *a, int n){    double bitcount = 1;    int begin = 0;    for(int i=2; i<=n; ++i) {        long add = 0; //源为long and=0;由于and是C++关键字,所以出错。                       //故所有为add的源文为and.不小心的出错点。        bitcount += log10((long double)i);        if(a[begin] == 0)            begin++;        for(int j=begin; j<int(bitcount); ++j) {            add += (i*a[j]);            a[j] = char(add % 10);            add /= 10;        }    }}void display(char *a, int size){    int bit = 0;    for(int i=size-1; i>;=0; i--) {        if(bit % 50 == 0)            cout << endl << "The"                << setw(5) << (bit/50+1) << " /'s 50 bit: ";        cout << int (a[i]); //思考:为什么需要进行显式的整形转换呢?        bit++;    }    cout << endl;}


最新回复(0)