public static function permutations(int $n, int $k = null) { if ($n < 0) { throw new Exception\OutOfBoundsException('Cannot compute negative permutations.'); } if (!is_null($k) && $k > $n) { throw new Exception\OutOfBoundsException('k cannot be larger than n.'); } $n! = self::factorial($n); // nPn: permutations of n things, taken n at a time if (is_null($k)) { return $n!; } // nPk: Permutations of n things taking only k of them $⟮n − k⟯! = self::factorial($n - $k); return $n! / $⟮n − k⟯!; }