How to find the divisors of a number in PHP

2 Answers

0 votes
function printDivisors($n) {
    for ($i = 1; $i <= $n; $i++) {
        if ($n % $i == 0) {
            echo $i . ", ";
        }
    } 
}
 
$n = 24;
printDivisors($n);



/*
run:

1, 2, 3, 4, 6, 8, 12, 24, 

*/

 



answered Jul 1, 2020 by avibootz
0 votes
function printDivisors($n) {
    for ($i = 1; $i <= sqrt($n); $i++) {
        if ($n % $i == 0) { 
            if ($n / $i == $i) 
                printf("%d, ",  $i); 
            else
                printf("%d, %d, ", $i, $n / $i); 
        } 
    } 
}


$n = 24;
printDivisors($n);



/*
run:

1, 24, 2, 12, 3, 8, 4, 6, 

*/

 



answered Jul 1, 2020 by avibootz

Related questions

1 answer 129 views
1 answer 88 views
2 answers 167 views
2 answers 251 views
2 answers 149 views
149 views asked Jul 1, 2020 by avibootz
2 answers 181 views
2 answers 165 views
165 views asked Jun 30, 2020 by avibootz
...