• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C++计算一个大数的阶乘

OC/C/C++ 水墨上仙 1413次浏览

C++计算一个大数的阶乘

// calculate large factorials (factorials above 12!)
// note that 13! already exceeds unsigned long
// a Dev-C++ tested console program  by  vegaseat  26mar2005 
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
  unsigned int nd, nz;   // number of digits
  unsigned char *ca;     // char array to hold result
  unsigned int j, n, q, temp;
  int i;
  double p;
    
  while(1)
  {
    cout << "\nEnter an integer to calculate factorial (0 to exit): ";
    cin >> n;
    
    if (n == 0) break;
     
    //calculate nd = the number of digits required
    p = 0.0;
    // p is really log10(n!)
    for(j = 2; j <= n; j++)
    {
      p += log10((double)j);   // cast to double
    }
    nd = (int)p + 1;
    // allocate memory for the char array
    ca = new unsigned char[nd];
    if (!ca)
    {
      cout << "Could not allocate memory!!!";
      exit(0);
    }
    //initialize char array
    for (i = 1; i < nd; i++)
    {
      ca[i] = 0;
    }
    ca[0] = 1;
    
    // put the result into a numeric string using the array of characters
    p = 0.0;
    for (j = 2; j <= n; j++)
    {
      p += log10((double)j);   // cast to double!!!    
      nz = (int)p + 1;         // number of digits to put into ca[]
      q = 0;                   // initialize remainder to be 0
      for (i = 0; i <= nz; i++)
      {
        temp = (ca[i] * j) + q;
        q = (temp / 10);
        ca[i] = (char)(temp % 10);
      }
    }
  
    cout << "\nThe Factorial of " << n << " is: ";
    // the factorial is stored in reverse, spell it from the back
    for( i = nd - 1; i >= 0; i--)
    {
      cout << (int)ca[i];
    }
    cout << endl;
    
    // free up allocated memory
    delete []ca;    
  }  // while
    	
  return 0;
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C++计算一个大数的阶乘
喜欢 (0)
加载中……