Open In App

PHP Program to Calculate Combination nCr

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

This article will show you how to Calculate the Combination nCr in PHP.

Combinations refer to the different ways in which a set of items can be selected without considering the order. In mathematics, the number of combinations of ‘n’ distinct items taken ‘r’ at a time is denoted as nCr. The formula for combinations is nCr = n! / (r! * (n-r)!), where ‘!’ denotes the factorial of a number.

What is nCr Formula?

The nCr represents “n choose r,” a concept in combinatorics that calculates the number of ways to select a group of items from a larger set without considering the order of selection. It is denoted mathematically as:

nCr = n! / (r!(n – r)!)

Where,

  • n is the total number of items in the set,
  • r is the number of items to be chosen, and
  • ! denotes factorial, which is the product of all positive integers from 1 to the given number.

Calculate Combination using Factorial Method in PHP

In this approach, we use factorial method to calculate the Combination i.e. nCr. The formula to calculate the combination is nCr = n! / (r! * (n-r)!).

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 combination
function combination($n, $r) {
    if ($n < $r) {
        return "Invalid input";
    }
  
    return factorial($n) / (factorial($r) * factorial($n - $r));
}
  
// Driver code
$n = 5;
$r = 2;
  
echo "Combination: " . combination($n, $r);
  
?>


Output

Combination: 10

Calculate Combination using Iterative Method in PHP

In this approach, we use iterative method to calculate the combination of given number.

PHP




<?php
  
function combination($n, $r) {
    if ($n < $r) {
        return "Invalid input";
    }
  
    $result = 1;
      
    for ($i = 0; $i < $r; $i++) {
        $result *= ($n - $i);
        $result /= ($i + 1);
    }
  
    return $result;
}
  
// Driver code
$n = 5;
$r = 2;
  
echo "Combination: " . combination($n, $r);
  
?>


Output

Combination: 10


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads