Created
November 6, 2018 20:26
-
-
Save quonic/a809e49db765ae178f3176843ab6ebd6 to your computer and use it in GitHub Desktop.
Get-Factor and Test-Prime functions that are fairly fast, for Powershell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-Factor { | |
param ( | |
[Parameter(Mandatory = $true, | |
Position = 0, | |
ValueFromPipeline = $true)] | |
[ValidateNotNullOrEmpty()] | |
[int64[]] | |
$Number, | |
[switch] | |
$Prime | |
) | |
Process { | |
$FactorCount = 0 | |
foreach ($num in $Number) { | |
for ($x = 1; $x -le $num; $x++) { | |
if ($Prime -and $FactorCount -gt 2) { | |
break | |
} | |
if ($num % $x -eq 0) { | |
$x | |
$FactorCount++ | |
} | |
} | |
} | |
} | |
} | |
Function Test-Prime { | |
param( | |
[Parameter(Mandatory = $true, | |
Position = 0, | |
ValueFromPipeline = $true)] | |
[ValidateNotNullOrEmpty()] | |
[int64[]] | |
$Number | |
) | |
Process { | |
if ($($Number | Get-Factor -Prime).Count -le 2) { | |
$Number | |
} | |
} | |
} | |
#1..100 | Test-Prime |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment