1:  /// -------- ToujoursEnBeta
   2:  /// Author & Copyright : Peter Luschny
   3:  /// License: LGPL version 3.0 or (at your option)
   4:  /// Creative Commons Attribution-ShareAlike 3.0
   5:  /// Comments mail to: peter(at)luschny.de
   6:  /// Created: 2010-03-01
   7:   
   8:  namespace Sharith.Math.Factorial 
   9:  {
  10:      using XInt = Sharith.Arithmetic.XInt;
  11:   
  12:      public class SwingSimple : IFactorialFunction  
  13:      {
  14:          public SwingSimple() { }
  15:          
  16:          public string Name
  17:          {
  18:              get { return "SwingSimple         "; }
  19:          }
  20:   
  21:          public XInt Factorial(int n)
  22:          {
  23:              if (n < 0)
  24:              {
  25:                  throw new System.ArgumentOutOfRangeException("n",
  26:                  Name + ": n >= 0 required, but was " + n);
  27:              }
  28:   
  29:              return RecFactorial(n);
  30:          }
  31:   
  32:          private XInt RecFactorial(int n)
  33:          {
  34:              if (n < 2) return XInt.One;
  35:   
  36:              return XInt.Pow(RecFactorial(n / 2), 2) * Swing(n);
  37:          }
  38:   
  39:          private static XInt Swing(int n)
  40:          {
  41:              int z;
  42:   
  43:              switch (n % 4)
  44:              {
  45:                  case 1: z = n / 2 + 1; break;
  46:                  case 2: z = 2; break;
  47:                  case 3: z = 2 * (n / 2 + 2); break;
  48:                  default: z = 1; break;
  49:              }
  50:   
  51:              var b = new XInt(z);
  52:              z = 2 * (n - ((n + 1) & 1));
  53:   
  54:              for (int i = 1; i <= n / 4; i++, z -= 4)
  55:              {
  56:                  b = (b * z) / i;
  57:              }
  58:   
  59:              return b;
  60:          }
  61:      }
  62:  } // endOfFactorialSwingSimple