PHP program to calculate factors of a given number
<?php
//We Define a function that gets
//an argument and return the factors
//of the number it got.
// Function definition
function factors_of_a_number($n)
{
if ($n == 0)
{
// because we cannot divide 0/0 does not exist
echo "Zero has no factors";
}
else
{
// format our answer to look good.
print_r("The factors of $n are {");
//We will use a for loop to loop through
// each number in the series 1 to our number $n
// dividing $n by each number
for ($x = 1;$x <= $n;$x++)
{
// the modulus operator
// helps us get the remainder of each division
$factor = $n % $x;
//we will check to see which number return a 0 as reminder
// the we echo that number because it is a factor of our number $n.
if ($factor == 0)
{
print_r($x . ",");
}
}
print_r("}");
}
}
print_r(factors_of_a_number(0) . "\n");
print_r(factors_of_a_number(50) . "\n");
?>
Output
Zero has no factors
The factors of 50 are {1,2,5,10,25,50,}
