Search code examples
phpfunctionfactorial

2 different number input factorial using function and for loop in php


I have a problem making a C(m,n)=m!/n!(m-n)! formula using a function and for loop in php, my code look like this:

<?php
function factorial($m,$n){
	$facm=$m;
	for ($i=$m-1; $i >= 1 ; $i--) { 
		$facm*=$i;
	}
	$facn=$n;
	for ($i=$n-1; $i >= 1 ; $i--) { 
		$facn*=$i;
	}
	$faco=$m-$n;
	for ($i=$m-$n; $i >= 1 ; $i--) { 
		$faco*=$i;
	}
	return $facm/$facn*$faco;
}
}

echo factorial($bilm,$biln);
?> 

but this code show wrong result, is it something wrong with my code? thank you for your attention.


Solution

  • Yes you can do like below if it is stick to 2 parameters. If the parameters are dynamically change, then pass array to the function and do a foreach there.

     <?php
        $bilm = $_POST['bilm'];
        $biln = $_POST['biln'];
    
        function factorial($m,$n){
    
                $facm=$m;
                for ($i=$m-1; $i >= 1 ; $i--) { 
                    $facm*=$i;
                }
    
                $facn=$n;
                for ($i=$n-1; $i >= 1 ; $i--) { 
                    $facn*=$i;
                }
    
                $facmsubn = $msubn=$m-$n;
                for ($i=$msubn-1; $i >= 1 ; $i--) { 
                    $facmsubn*=$i;
                }
    
                return ($facm/$facn)*$facmsubn; //By assuming (m!/n!)*(m-n)!; If it is m!/(n!*(m-n)!) then change the logic as per your formula
       }
              echo factorial($bilm,$blin);
        ?>
    

    But why you need pass 2 parameters? Calling the function twice would make sense.

    Runtime environment is here http://phpfiddle.org/main/code/zkfs-21am