permutations

Back to: **Arbitrary-Precision Math**

The function defined here computes the total possible number of permutations there are within a population of **N** unique items selected in groups of **R** at a time. We often see this operation written something like:

When it comes to the number of permutations (**P**), the order or sequence of the **R** items, as extracted from a total population of **N**, is fundamentally important as *the permutations equate to a total count of all the unique sequences that can be formed* from the given population, if we only select lineups of **R** of them at a time.

Since these computations are done in arbitrary-precision, they could result in very large values extending out to hundreds or thousands of digits.

**Permutations Calculator** based on the function defined below.

**The function used to perform the P(N,R) computation follows below.**

/* ======================================================================== This function returns the permutations of (N) items taken (R) at a time. Like the digits of a number or the letters in a word, the sequential order of the selected items is important. Input arguments must be positive integers. Any decimal argument will be truncated to an integer, without rounding, rather than returning an error. ERRORS: FALSE is returned on error, if either argument is non-numeric or out of valid range. ======================================================================== */ function bcPerm_N_R ($IntN, $IntR) { // Read input arguments. $N = trim($IntN); $R = trim($IntR); // Error if either argument is non-numeric. if (!is_numeric($N) or !is_numeric($R)) {return FALSE;} // Truncate argument(s) to integer value(s) without rounding. $N = bcadd($N, 0); $R = bcadd($R, 0); // Error if either argument is out of valid range. if ($N < 0 or $R < 0 or $R > $N) {return FALSE;} // Execute loop to compute P(N, R). $P=1; for ($i=0; $i < $R; $i++) {$P = bcmul($P, $N-$i);} // Done. return $P; }

**This is a test program to demonstrate the above function followed by the full source code.**

Permutations of N=24 distinct items if taken in groups of R=8 at a time: The exact value of P (N,R) = 29654190720 Digits Count = 11

<?php // Permutations: P = P(N, R) // Generate random values for example. $N = mt_rand(10, 9999); $R = mt_rand(1, $N); // Cannot exceed N value above. $P_NR = bcPerm_N_R($N, $R); $DigitsCount = strlen($P_NR); print "<pre> Permutations of N=$N distinct items if taken in groups of R=$R at a time: The exact value of P (N,R) = $P_NR Digits Count = $DigitsCount </pre>"; // ================================== function bcPerm_N_R ($IntN, $IntR) { $N = trim($IntN); $R = trim($IntR); if (!is_numeric($N) or !is_numeric($R)) {return FALSE;} $N = bcadd($N, 0); $R = bcadd($R, 0); if ($N < 0 or $R < 0 or $R > $N) {return FALSE;} $P=1; for ($i=0; $i < $R; $i++) {$P = bcmul($P, $N-$i);} return $P; } ?>

permutations.txt · Last modified: 2014/04/08 01:56 (external edit)