c++ - Can anyone explain this algorithm for calculating large factorials? -
I have come to the following program to calculate the large factorials (greater than 100). Somebody can tell me the basic idea Is used in this algorithm ?? I need to know the fact that in fact mathematical calculations have been done.
  #include & lt; Cmath & gt; # Include & lt; Iostream & gt; # Include & lt; Cstdlib & gt; using namespace std; Int main () {unsigned int d; Unsigned char * a; Unsigned int j, n, q, z, t; Int I, ARR [101], F; Double P; CIN & gt; & Gt; N; P = 0.0; For (j = 2; j; l; = n; j ++) p + = log 10 (j); D = (int) p + 1; A = new unsigned char [D]; For (i = 1; i & lt; d; i ++) a [i] = 0; // start [0] = 1; P = 0.0; For (j = 2; j; l; = n; j ++) {q = 0; P + = Log 10 (J); Z = (int) P + 1; For (i = 0; i & lt; = z / * NUMDIGITS * /; i ++) {T = (a [i] * j) + q; Q = (T / 10); A [i] = (four) (t% 10); }} For (I = D -1; I> = 0; I -) COAT & LT; & Lt; (Integer) a [i]; The court's & lt; & Lt; "\ N"; Delete [] A; Return 0; }   
Note that
  n! = 2 * 3 * ... * n   so
  log (n!) = Log (2 * 3 * ... * n) = Log (2) + log (3) + ... + log (n)    This is important because if  k  is a positive integer  The maximum limit of log (s)  is in the representation of base code 10 in  k . Thus, these lines of code  n! Calculating the number of digits in . 
  p = 0.0; For (j = 2; j; l; = n; j ++) p + = log 10 (j); D = (int) p + 1;    Then, these lines of code  n! Allocate space to hold digits of  
  a = new unsigned char [d]; For (i = 1; i & lt; d; i ++) a [i] = 0; // initialize   Then we just do grade-grade multiplication algorithm
  p = 0.0; For (j = 2; j; l; = n; j ++) {q = 0; P + = Log 10 (J); Z = (int) P + 1; For (i = 0; i & lt; = z / * NUMDIGITS * /; i ++) {t = (a [i] * j) + q; Q = (T / 10); A [i] = (four) (t% 10); }}    External loop  j  to  2  to  n  because we are currently in each step The code will be indicated by  a  to  j . The internal loop is the grade-school multiplication algorithm in which we multiply each digit by  j  and if it is necessary, take the result in  q . 
  P = 0.0  Before the nested loop and in the  p + = log10 (j)  loop, just keep track of the number of digits in the reply so far . 
 Incidentally, I think there is a bug in this part of the program. Loop status     Then we print digits only For   and free allocated memory  i & lt; Z  not  i  
  for (i = 0; i & lt; = z / * NUMDIGITS * /; i ++) by   For 
  (i = 0; i & lt; z / * NUMDIGITS * /; i ++)   
  (I = D -1; I> = 0; I -) COAT & LT; & Lt; (Integer) a [i]; The court's & lt; & Lt; "\ N";   
  delete [A] A;  
Comments
Post a Comment