Skip to content

Instantly share code, notes, and snippets.

@quonic
Created November 6, 2018 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quonic/a809e49db765ae178f3176843ab6ebd6 to your computer and use it in GitHub Desktop.
Save quonic/a809e49db765ae178f3176843ab6ebd6 to your computer and use it in GitHub Desktop.
Get-Factor and Test-Prime functions that are fairly fast, for Powershell
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