Open In App

PHP gmp_binomial() Function

Last Updated : 25 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The gmp_binomial() function is an inbuilt function in PHP that is used to calculate the binomial coefficients. The binomial coefficient, often denoted as “n choose k” or “C(n, k)”, represents the number of ways to choose “k” elements from a set of “n” distinct elements without regard to the order.

Syntax:

gmp_binomial(GMP|int|string $n, int $k): GMP

Parameters: This function accepts two parameters that are described below.

  • $n: This parameter must be an integer.
  • $k: This parameter must be an integer type. If this parameter is negative. It will occur the error.

Return Value: The gmp_binomial() function returns the coefficient of the numbers c(n, k) ;

Program 1: The following program demonstrates the gmp_binomail() function.

PHP




<?php
  
// Assuming you have the GMP extension enabled
$n = 6 ;
$k = 2 ;
$binomialCoefficient = gmp_binomial($n, $k);
  
echo "Binomial Coefficient C($n, $k) is: "
      . $binomialCoefficient . "\n";
?>


Output

Binomial Coefficient C(6, 2) is: 15

Program 2: The following program demonstrates the gmp_binomail() function.

PHP




<?php
  
// Assuming gmp library in enable in your PHP
  
try {
    $n = 5; // Total number of distinct elements
    $k = -2 ;
      
      if($k < 0) {
        throw new Exception("$k value must be greater than 0") ;
    }
    
      $binomialCoefficient = gmp_binomial($n, $k);
        
    echo "Binomial Coefficient C($n, $k) is: "
          . $binomialCoefficient . "\n";
       } catch(Exception $e) {
          echo $e->getMessage() ;
}
  
?>


Output:

k value must be greater than 0 

Reference: https://www.php.net/manual/en/function.gmp-binomial.php



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads