Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python math.factorial algorithm

bigint Factorial(int n)
  {
      bigint p = 1, r = 1;
      loop(n, p, r);
      return r << nminussumofbits(n);
  }

  loop(int n, reference bigint p, reference bigint r)
  {
      if (n <= 2) return;
      loop(n / 2, p, r);
      p = p * partProduct(n / 2 + 1 + ((n / 2) & 1), n - 1 + (n & 1));
      r = r * p;
  }

  bigint partProduct(int n, int m)
  {
      if (m <= (n + 1)) return (bigint) n;
      if (m == (n + 2)) return (bigint) n * m; 
      int k =  (n + m) / 2;
      if ((k & 1) != 1) k = k - 1;
      return partProduct(n, k) * partProduct(k + 2, m);
  }

  int nminussumofbits(int v)
  {
      long w = (long)v;
      w -= (0xaaaaaaaa & w) >> 1;
      w = (w & 0x33333333) + ((w >> 2) & 0x33333333);
      w = w + (w >> 4) & 0x0f0f0f0f;
      w += w >> 8;
      w += w >> 16;
      return v - (int)(w & 0xff);
  }
Source by www.luschny.de #
 
PREVIOUS NEXT
Tagged: #python #algorithm
ADD COMMENT
Topic
Name
6+1 =