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

  web : php functions : factorial()Share  


factorial()


Syntax:

string factorial ( 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; optional argument


Description:

This function will calculate the factorial n! of a positive integer or zero. Will also calculate the logical simplification of the equation n!/k! if k is specified in the second argument. 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

/* calculates n!/k! */
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.06
2009.02.05 17.26