Wednesday, January 15, 2014

Finding Whole Squares for a given number range in Powershell


I have never been very good at math.  My daughter, however, is a whiz and I find myself upgrading my skill sets to make sure I stay ahead of her enough to qualify as a mentor(!).  As part of her math team efforts, she needed to find the number of whole squares from 0..1000 inclusive.  This is a pretty simple problem  which can be done on a blackboard, calculator or in Powershell:

[math]::sqrt(1000)
31.6227766016838

There are 31 whole squares in the number range 0..1000.  You can find 999 of the squares from 0..1000 and filter out all the whole squares from that group like as in the truncated result below:

rv -ea 0 a
for ($i=1; $i -lt 1000; $i++) {[array]$a+=$([math]::sqrt($i))}
0..($a.count - 1) | % {$a.item($PSItem)} | ? {([float]$PSItem - [int]$PSItem) -eq 0}
1
2
3
...
29
30
31

With not too much more effort you can create a hashtable of all these squares and their square roots:

foreach ($i in $a) {$c+=[ordered]@{$i=$([math]::pow([double]$i,2));}}


Name                           Value
----                           -----
1                              1
1.4142135623731                2
1.73205080756888               3
2                              4
2.23606797749979               5
2.44948974278318               6
2.64575131106459               7
2.82842712474619               8
3                              9
3.16227766016838               10
...