Code Pyre

All Code Dies and Burns in Time

Fork me on GitHub

Project Euler: Problem 10 in PowerShell

| Comments

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

This problem is very simple as I can reuse the parasitic prime generation from my solution to Problem 7 which also requires Prototype.ps.

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 New-PrimeFinder {
  $prototype = New-PrimeGenerator
  $prototype | Add-Function FindPrimesLessThan {
    param($value)
    if($this.Bound -lt $value) {
      $finder.BoundIncrement = $value - $this.Bound
      $this.Expand()
    }
    return $this.Primes | ? { $_ -lt $value }
  }
  $prototype
}

function Solve-Problem10 {
  param($value = 2000000)
  $finder = New-PrimeFinder
  $finder.FindPrimesLessThan($value) | % {[long]$sum = 0} {$sum+=$_} {$sum}
}

Write-Host "Elapsed Time (s): " (Measure-Command {Solve-Problem10}).TotalSeconds
Write-Host "Solution: " (Solve-Problem10)

Elapsed Time (s):  1999.6739304
Solution:  142913828922

Comments