PowerShell_unix PowerShell is definitely gaining momentum in the windows scripting world but I still hear folks wanting to rely on Unix based tools to get their job done.  In this series of posts I’m going to look at converting some of the more popular Unix based tools to PowerShell.

factor

The Unix “factor” command will print out the Prime Factors of each number.  Factors are numbers, when multiplied together, give the original number.  Prime Factors are factors that are Prime Numbers (numbers that can be divided evenly only by one and itself).

The algorithm the Unix command is not very sophisticated so for some inputs this runs for a long time.  Essentially the algorithm (in the Get-PrimeFactors function) performs a linear search from 2 to the square root of the given number.  If a prime factor is found, then the algorithm is recursively run on the remaining (prime or composite) factor.

There are no command line arguments outside of the list of numbers.  I’ve implemented this list as an array in the “-numbers” argument.

I’ve included a bonus Get-Factors function that lists out all the factors (prime or composite) of the given numbers.  This feature isn’t included in the Unix “factor” command but I worked out the code so I figured I’d toss it in there in case it ever came in handy.