2008 Scripting Games - Advanced Event 6
Event 6: Prime Time
function Test-Prime ($num){ $prime = new-object psobject add-member -inp $prime noteproperty Number $null add-member -inp $prime noteproperty IsPrime $true $prime.Number=$num if($num -eq 2) { $prime.IsPrime=$true } else { foreach ($i in 2..([math]::Sqrt($num))) { if ($num % $i -eq 0) {$prime.IsPrime=$false } } } $prime } 1..200 | foreach {Test-Prime $_} | Where {$_.IsPrime} | select number | ft -auto
Number
------
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
2 comments:
Hi Shay,
I had a pretty similar solution, using [Math]::Sqrt().
I did some calcs with measure-command and found some interesting results. The call into .NET [math] actually took longer than going all the way to $num in the for loop for me.
http://get-powershell.com/2008/02/26/scripting-games-event-6-select-prime/
Andy
http://www.get-powershell.com
That's interesting. measure-command is such an important cmdlet.
Thank you for posting that.
Post a Comment