All Factors of a Number using Square Root Optimization
Since factors come in pairs (except for perfect squares), we only need to iterate up to the square root of the given number.
<?php
function findFactors($num) {
$factors = [];
for ($i = 1; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
$factors[] = $i;
if ($i != $num / $i) {
$factors[] = $num / $i;
}
}
}
sort($factors);
return $factors;
}
// Driver Code
$num = 12;
$factors = findFactors($num);
echo "Factors: " . implode(", ", $factors);
?>
Output
Factors: 1, 2, 3, 4, 6, 12
In this approach, we iterate up to the square root of the given number. For each factor we find, we also add its pair (the result of dividing the number by the factor) to the list of factors.
PHP Program to Find all factors of a Number
Given a Number, the task is to find all factors of the number in PHP. Factors are numbers that divide another number without leaving a remainder. In this article, we will cover all approaches to find all factors of a number using PHP.
Table of Content
- Using a Loop
- Using Square Root Optimization
- Using Recursion