Project Euler meets Powershell - isprime
I’ve read that an integer p > 1 is prime if and only if the factorial (p - 1)! + 1 is divisible by p. So I’ve written this:
function isprime {
[cmdletbinding()]
param([int] $x)
if ($x -lt 1) {
return "Has to be on a positive integer"
}
# An integer p > 1 is prime if and only if the factorial (p - 1)! + 1 is divisible by p
[int] $factorial = factorial ($x-1)
Write-Verbose "Factorial: $factorial"
$remainder = ($factorial + 1) % $x
Write-Verbose "Remainder: $remainder"
if ($remainder -eq 0) {
return $true
} else {
return $false
}
}
Unfortunately it doesn’t work for some numbers known to be prime - 29 is the example I have…