Scientific Calculator

(public) bthiessen/subfactorial

By bthiessen bthiessen

Subfactorial: (derangement) permutation of the elements of a set, such that no element appears in its original position

Tagged: enumerative combinatorics

subfactorial = function(n) {
     var x = 1;
     if (n == 1) -> x=0;
     if (n < 0) -> x="Error: argument must be a non-negative integer";
     if (n > 1) -> (
          var a = 1;
          var sign = -1;
          x = n!;
          while (a <= n) -> (
               x += sign * (n!/a!);
               a += 1;
               sign = sign * -1;
          );
     );
     x;
}

spam? | offensive?

0 Comments

Sign in to leave a comment