I have the following PowerShell function that works well for any input except for 1
. If I pass it an input of 1
it will return an array with two elements 1,1
instead of a single element which is itself an array of two elements (1,1)
.
Any ideas how I can make PowerShell return a jagged array with one element that is itself an array?
function getFactorPairs {
param($n)
$factorPairs = @()
$maxDiv = [math]::sqrt($n)
write-verbose "Max Divisor: $maxDiv"
for($c = 1; $c -le $maxDiv; $c ++) {
$o = $n / $c;
if($o -eq [math]::floor($o)) {
write-debug "Factor Pair: $c, $o"
$factorPairs += ,@($c,$o) # comma tells powershell to add defined array as element in existing array instead of adding array elements to existing array
}
}
return $factorPairs
}
Here is my test and it's output showing the problem. You can see that the first example (1 as input) is returning a length of 2 even though there was only one factor pair found. The second example (6 as input) is working properly and is returning a length of 2 with two factor pairs found.
~» (getFactorPairs 1).length
DEBUG: Factor Pair: 1, 1
2
~» (getFactorPairs 6).length
DEBUG: Factor Pair: 1, 6
DEBUG: Factor Pair: 2, 3
2