davidaltherr.net  home  |  journal  |  maps  |  archive  |  resume   

  web : php functions : nCk()Share  


nCk()


Syntax:

string nCk ( n , k )


Arguments:

stringna positive integer of arbitrary digit length or zero; must be passed as a string for values beyond the capacity of numeric types

stringka positive integer of arbitrary digit length or zero less than or equal to n; must be passed as a string for values beyond the capacity of numeric types


Description:

This function will calculate nCk, the number of combinations of k elements that can be taken from a (typically larger) set of n elements. Uses the math functions of the BC math library extension: arguments must be passed as strings, for values beyond the capacity of numeric types, and the function always returns a string, but it can handle virtually any size string.


Source:

<?php

/* quantifies combinations of size k taken from set n */
function nCk($n,$k){

    
/* cast args as string types */
    
$n = (string) $n;
    
$k = (string) $k;
    
    
/*
     *    typical equation form: n!/(k!(n-k)!)
     *    equivalent: nPk/k!
     *        where nPk = n!/(n-k)!
     */

    /* calculate */
    
$result bcdiv(factorial($n,bcsub($n,$k)),factorial($k));

    return 
$result;  // string
}

/* required function: factorial */
function factorial($n,$k='1'){

    
/* cast args as string types */
    
$n = (string) $n;
    
$k = (string) $k;
    
    
/* multiply iteratively */
    
$result '1';
    
$k bcadd($k,'1');
    for(
$xth=$k;bccomp($xth,$n)<1;$xth=bcadd($xth,'1')){
        
$result bcmul($result,$xth);
    }

    return 
$result// string
}


/*
*    Copyright 2001 David Altherr;
*        altherda@email.uc.edu
*        www.davidaltherr.net
*
*    Free for use under MIT open source public license
*/

?>



I host at Modwest because...

 search 
 

advanced search... 

 php | mysql 

boolean search 

relevance_pic() 

factorial() 

nCk() 

nPk() 

Powerful Hosting at Modwest...
 



  copyleft © 2010 david altherr
  free for use by open source license
  view: full | compact | mobile | print 

today:  
updated:  
2010.03.10 8.11
2009.02.05 17.26