PowerShell – Sum of the Squares

by Doug Finke on April 19, 2007

in PowerShell

After reading a bit about map, filter and lists. Here is a PowerShell approach.

Create Filter definitions

PS C:\> filter sum {process{$sum+=$_} end{$sum} }

PS C:\> filter square {$_ * $_}

PS C:\> filter even { if($_ % 2 -eq 0) {$_} }

The sum of the squares of the first 100 positive integers

PS C:\> 1..100 | square | sum

338350

The sum of the squares of the even numbers in the range 1 to 10

PS C:\> 1..10 | even | square | sum

220 

One Liner

PS C:\> 1..100 |% {$_*$_}|% {$s=0}{$s+=$_}{$s}

338350

{ 0 comments… add one now }

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>