PowerShell and Project Euler

By Michael Flanakin @ 1:40 PM :: 1812 Views :: Development, PowerShell :: Digg it!

PowerShell

So, my "daily" PowerShell tips haven't gone like I imagined. I have a list of topics to post. I just haven't had the time to type them all out. Either way, I'm still stuck on PowerShell. As a matter of fact, I just heard about a geeky website, Project Euler, which is dedicated to math and programming problems. When I first heard about it, I was thinking it sounded like a great way to hone your performance tuning skills. After trying the first problem, I'm not sure that's the case, but the problem was very simple. As a matter of fact, I solved it with a one-liner. If you're actually interested in solving it yourself, you may want to ignore this post. Then again, it's pretty simple.

I'll probably check out more of these. I'm not sure if I'll post the andwers or not, tho. Then again, as you progress, they get more and more complicated. If you're a sucker for pain, you can jump to one of the more complicated problems. I don't know how hard they'll be, but I'm sure it'll take longer than the 2 minutes this one took me.

Problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

My Solution

All I did was loop tthrough all numbers and added the number to a running tally if it was divisible by 3 or 5. Gee, that's pretty much what the problem statement was. Like I said, this one is pretty simple.

$sum = 0; ForEach-Object ($i in 3 .. 10) { if ((($i % 3) -eq 0) -or (($i % 5) -eq 0)) { $sum += $i } }; Write-Output $sum

What really surprised me was that this script ran from 3 to 1000 in 0.0156 seconds. I don't know what typical numbers are, but I was expecting it to take longer. For learning purposes, the aliases for ForEach-Object and Write-Output are foreach and echo.

Ratings