-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactors.php
More file actions
44 lines (33 loc) · 835 Bytes
/
Copy pathfactors.php
File metadata and controls
44 lines (33 loc) · 835 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
// write a function that will return an array of all factors of a given integer
function findFactors($int) {
// your code here
}
var_dump(findFactors(64));
var_dump(findFactors(15));
var_dump(findFactors(0));
// one possible solution
function findFactors($int) {
$results = [];
$half = ceil($int/2);
for($i = 1; $i <= $half; $i++) {
if($int % $i == 0) {
$otherHalf = $int/$i;
if(!isset($results[$otherHalf])) { // avoid duplicate pairs
$results[$i] = $int/$i;
}
}
}
return $results;
}
// another
function findFactors($int) {
$results = [];
$max = ceil(sqrt($int));
for($i = 1; $i <= $max; $i++) {
if($int % $i == 0) {
$results[$i] = $int/$i;
}
}
return $results;
}