header image

Summing multiples

Posted by: | February 22, 2019 Comments Off on Summing multiples |

Came across the project Euler web site – https://projecteuler.net. It has literally hundreds of problems – mainly mathematical – that’ll illustrate some useful PowerShell techniques. The first problem is summing multiples.


You need to sum all of the multiples of 3 or 5 below 1000.


The first thing to do is to read the problem very carefully. Using the supplied example of multiples of 3 or 5 below 10 you don’t include 1000 in the solution. Its less than not less than or equal to.


The PowerShell solution is one pipeline:

1..999 |
Where-Object {($_ % 3) -eq 0 -OR ($_ % 5) -eq 0} |
Measure-Object –sum


Use the range operator to put the numbers 1 to 999 on to the pipeline. Use Where-Object to filter for multiples of 3 or 5. The filter consists of performing modulo arithmetic of the number and accepting those numbers where the result is zero i.e. a multiple of 3 or a multiple of 5


You don’t need to worry about numbers that are multiples of 3 AND 5 as the –OR in the Where-Object passes the number when the first test is passed.


The sum is calculated using Measure-Object.

under: PowerShell

Comments are closed.