function Factorial($x) { if ($x < 1) { echo "Factorial() Error: Number too small!"; }
This is not true, 0! = 1 0! = 1 defined, so the test should be $x < 0 .
$ans = 1; for ($xx = 2; $xx >= $x; $xx++)
You sealed the condition, it should be $xx <= $x .
function Combination($selectcount,$availablecount) { $ans = Factorial($availablecount) / ( Factorial($availablecount - $selectcount) * Factorial($selectcount) ); return ($ans); }
Here you have two potential problems,
- the
Factorial function call is slower than the loop calculating the combination counter here - factorials become very large, so you run the risk of overflow and inaccuracies where you don't need to
Whether these are actual problems depends on your application. You wrote that the results fall into the array, apparently, to avoid recalculation, so the speed for the initial calculation is less important. However, problems with overflow may well be. To avoid this, calculate the array entries recursively on the Pascal triangle, choose(n+1,k) = choose(n,k) + choose(n,k-1) , where choose(n,k) = 0 if k < 0 or k > n . Alternatively, you can calculate each row starting with choose(n,0) = 1 and choose(n,k) = choose(n,k-1)*(n+1-k)/k for 1 <= k <= n . Both methods avoid the large intermediate n! and thus give accurate results for a wider range of numbers.
source share