Find the sum of all the multiples of 3 or 5 below 1000
What do you think?
- Version 1 captures the essence better, less ceremony than Version 2
- Version 2 is faster PowerShell – Four For Loops and their timings
- Version 2 is a more recognizable way of coding
- Version 1 requires more work to understand if you’re not used to it
Version 1
0..999 | Where {$_ % 3 -eq 0 -Or $_ % 5 -eq 0 } | ForEach {$total=0} {$total+=$_} {$total}
Version 2
$total=0 for($i=0; $i -lt 1000; $i+=1) { if($i % 3 -eq 0 -Or $i % 5 -eq 0) { $total+=$i } } $total





{ 8 comments… read them below or add one }
isn’t that the for-if-antipattern?
http://blogs.msdn.com/b/oldnewthing/archive/2011/12/27/10251210.aspx
Anyway, this is an http://en.wikipedia.org/wiki/Arithmetic_progression
This brings back memories from some long forgotten math exams
You can use the Euler Sum (as a tribute to the man himself). No loops nor comparisons.
Sum the multiples of 3 and 5, and then subtract the 15 multiples.
function Get-EulerSum{
param($Max,$Step)
$numberOfMultiples = [math]::Floor(($max-1)/$step)
$t = [math]::Floor(($max-1)/$step)
$numberOfMultiples / 2 * ($step + $step * $t)
}
$total = 0
$total += Get-EulerSum -Max 1000 -Step 3
$total += Get-EulerSum -Max 1000 -Step 5
$total -= Get-EulerSum -Max 1000 -Step 15
$total
Thanks for the comments.
Andreas, indeed that is the for-if antipattern in Version 2.
Luc great example.
A colleague did a presentation, writing a LISP engine in the Lua language. He opened with loops and [mutable] variables are evil.
I would certainly say version 1 is a better version; it’s performance is equivalent to V2, and I would argue that it’s clearer to read in its declarativeness.
I wish you hadn’t mentioned Project Euler
. I had stopped playing with that years ago. Now you made me go and solve 3 more problems. Kudos for using PowerShell, though. I’ll have to see how well that works. I had been using Python previously.
Thanks Mike. I find using Project Euler, even with new languages, helps me get my bearings. Some of the problems are small enough allowing you dig deeper and wider at the language itself.
Doug
That’s exactly how I used it. I was looking for something to play around with using Python, and didn’t really want to fight with developing an “application”. I’ve got a math background and the ProjectEuler problems are pretty interesting. I was able to get a decent handle on Python syntax and some of the standard libraries this way.
Are you planning on attempting solutions for other problems using PowerShell?
Great approach! Yes, I am looking to do that as soon as I have time. Check out Wes Stahler, he has blogged many of his Project Euler PowerShell Solutions.