Advertisement
Guest User

Untitled

a guest
Jun 8th, 2014
431
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.98 KB | None | 0 0
  1. int
  2. factdigsum (unsigned border)
  3. {
  4.   #define GROUPING 1000000
  5.   unsigned dig [border + 1]; /* digits grouped by log10 (GROUPING) */
  6.   unsigned first = 0, last = 0, carry, n, x, sum = 0;
  7.  
  8.   dig [0] = 1;
  9.  
  10.   for (n = 2; n != border; ++n)
  11.     {
  12.       carry = 0;
  13.  
  14.       /* multiplying */
  15.       for (x = first; x < last + 1; ++x)
  16.         {
  17.           unsigned nxt;
  18.           nxt = dig [x] * n + carry;
  19.           dig [x] = nxt % GROUPING;
  20.           if ((x == first) && ((nxt % GROUPING) == 0))
  21.             {
  22.               first += 1;
  23.             }
  24.           carry = nxt / GROUPING;
  25.         }
  26.  
  27.       /* opening new digit group */
  28.       if (carry != 0)
  29.         {
  30.           last += 1;
  31.           dig [last] = carry;
  32.         }
  33.     }
  34.  
  35.   /* now we may calculate sum of digits */
  36.   for (x = first; x < last + 1; ++x)
  37.     {
  38.       unsigned g = GROUPING;
  39.       while (g > 9)
  40.         {
  41.           g = g / 10;
  42.           sum += (dig [x] / g) % 10;
  43.         }
  44.     }
  45.  
  46.   return sum;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement