PHP Program to Calculate the Permutation nPr
Last Updated :
27 Dec, 2023
This article will show you how to calculate the Permutation nPr using PHP.
Permutations refer to the different ways in which a set of items can be arranged. In mathematics, the number of permutations of ‘n’ distinct items taken ‘r’ at a time is denoted as nPr. Calculating nPr, or permutations means finding the number of unique ordered arrangements of r items from a set of n distinct items. Where order matters and no item is repeated.
The formula for calculating permutations is n factorial divided by (n-r) factorial where n and r are integers and n is greater than or equal to r. The mathematical representation is as follows:
P(n, r) = n! / (n - r)!
For n ≥ r ≥ 0
Factorial Method
The formula for permutations is nPr = n! / (n-r)!, where ‘!’ denotes the factorial of a number. The factorial of a number is the product of all positive integers up to that number.
Example:
PHP
<?php
function factorial( $n ) {
if ( $n == 0 || $n == 1) {
return 1;
} else {
return $n * factorial( $n - 1);
}
}
function permutation( $n , $r ) {
if ( $n < $r ) {
return "Invalid input" ;
}
return factorial( $n ) / factorial( $n - $r );
}
$n = 5;
$r = 2;
echo "Permutation: " . permutation( $n , $r );
?>
|
Iterative Method
This approach calculates permutations using an iterative loop.
Example:
PHP
<?php
function permutation( $n , $r ) {
if ( $n < $r ) {
return "Invalid input" ;
}
$result = 1;
for ( $i = 0; $i < $r ; $i ++) {
$result *= ( $n - $i );
}
return $result ;
}
$n = 5;
$r = 2;
echo "Permutation: " . permutation( $n , $r );
?>
|
Share your thoughts in the comments
Please Login to comment...