Open In App

PHP Program to Calculate the Permutation nPr

Last Updated : 27 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 to calculate factorial
function factorial($n) {
    if ($n == 0 || $n == 1) {
        return 1;
    } else {
        return $n * factorial($n - 1);
    }
}
  
// Function to calculate permutations
function permutation($n, $r) {
    if ($n < $r) {
        return "Invalid input";
    }
  
    return factorial($n) / factorial($n - $r);
}
  
// Driver code
$n = 5;
$r = 2;
  
echo "Permutation: " . permutation($n, $r);
  
?>


Output

Permutation: 20

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;
}
  
// Driver code
$n = 5;
$r = 2;
  
echo "Permutation: " . permutation($n, $r);
  
?>


Output

Permutation: 20


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads