Code Pyre

All Code Dies and Burns in Time

Fork me on GitHub

Project Euler: Problem 9 in PowerShell

| Comments

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function Solve-Problem9 {
  $sum = 1000
  $found = $false
  for ($a = 1; $a -lt $sum / 3; $a++) {
    for ($b = $a; $b -lt $sum / 2; $b++) {
      $c = $sum - $a - $b

      if ($a * $a + $b * $b -eq $c * $c) {
        $found = $true
        break
      }
    }

    if ($found) { break }
  }

  Write-Host "The Pythagorean triplet is a = $a, b = $b, c = $c"
  Write-Host "The product is $($a*$b*$c)"
}

Write-Host "Elapsed Time (s): " (Measure-Command {Solve-Problem9}).TotalSeconds
The Pythagorean triplet is a = 200, b = 375, c = 425
The product is 31875000
Elapsed Time (s):  0.2247551

Comments