Expand/Shrink

factorial / k_perm / choose

Definition: atom res = factorial(atom n)
-- or --
atom res = k_perm(integer n, k)
-- or --
atom res = choose(integer n, k)
Description: factorial(): standard iterative factorial function, with memoisation.
k_perm(): standard partial permutations calculation (sequences without repetition).
choose(): standard combinations calculation - choose k from n aka "n choose k"
pwa/p2js: Supported.
Comments: factorial() returns infinity for n>170 on 32-bit, and for n>1754 on 64-bit.

Atoms on 32-bit are limited to 53 bits of precision, which means that the largest factorial which can be held exactly is 18 on 32-bit and 20 on 64-bit, anything above that up to the limits just given are approximations. There is also an mpz version, mpz_fac_ui(), with far higher limits, and perfect accuracy.

The k_perm() routine calculates the result directly, rather than via the slightly less efficient (/limit-exceeding) way of using complete factorials, ie n(n-1)..(n-k-1) rather than n!/(n-k)!, and choose() simply divides that by k!.
Implementation: See builtins\factorial.e (an autoinclude) for details of the actual implementation.
Example:
--            n : 0 1 2 3 4  5   6   7    8
--  factorial(n): 1 1 2 6 24 120 720 5040 40320 
See Also: mpz_fac_ui, mpz_bin_uiui