Skip to content

Commit d75fd89

Browse files
authored
Add Prime Number in PowerShell (#4735)
1 parent b6ce2f8 commit d75fd89

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

archive/p/powershell/PrimeNumber.ps1

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
function Show-Usage() {
2+
Write-Host "Usage: please input a non-negative integer"
3+
Exit 1
4+
}
5+
6+
function Test-IsPrime([int]$Value) {
7+
if ($Value -lt 2 -or ($Value -ne 2 -and $Value % 2 -eq 0)) {
8+
return $false
9+
}
10+
11+
$Q = [Math]::Floor([Math]::Sqrt($Value))
12+
for ($X = 3; $X -le $Q; $X += 2) {
13+
if ($Value % $X -eq 0) {
14+
return $false
15+
}
16+
}
17+
18+
$true
19+
}
20+
21+
if ($args.Length -lt 1) {
22+
Show-Usage
23+
}
24+
25+
try {
26+
$Value = [int]::Parse($args[0])
27+
} catch {
28+
Show-Usage
29+
}
30+
31+
if ($Value -lt 0) {
32+
Show-Usage
33+
}
34+
35+
Write-Host ((Test-IsPrime $Value) ? "prime" : "composite")

0 commit comments

Comments
 (0)