All Factors of a Number using Recursion
We can also use recursion to find all factors. In recursion, we call the same function again and again to find all factors of number.
<?php
function findFactors($num, $i = 1, $factors = []) {
if ($i > sqrt($num)) {
sort($factors);
return $factors;
}
if ($num % $i == 0) {
$factors[] = $i;
if ($i != $num / $i) {
$factors[] = $num / $i;
}
}
return findFactors($num, $i + 1, $factors);
}
// Driver Code
$num = 12;
$factors = findFactors($num);
echo "Factors: " . implode(", ", $factors);
?>
Output
Factors: 1, 2, 3, 4, 6, 12
In this approach, the function calls itself recursively, incrementing the divisor until it reaches the square root of the given number.
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