Solving Programming Problems with PowerShell (Problem 3)

I recently read a blog post by Santiago Valdarrama about developer programming problems. He said that any programmer should be able to solve five problems in an hour or less with a programming language of his choice. My language of choice is PowerShell, which is probably not what he had in mind when he wrote the blog post. So far, I’ve demonstrated In adding numbers in an array three different ways and merging lists together. Problem 3 is a classic – the Fibonacci Series Calculation.

Problem 3: Fibonacci Numbers

The Fibonacci Series is a classic numerical problem. The first two numbers in the series are 0 and 1. After that, the next element is the sum of the previous two numbers. The problem statement is this:

Write a function that computes the list of the first 100 Fibonacci numbers. By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. As an example, here are the first 10 Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.

There are two ways of doing this – recursion and a simple loop. I always avoid recursion if I can – it can so easily go wrong. So I’ll do a loop method. I also will not use an array – just two numbers.

Here is my code:

function New-FibonacciSeries
        # Number of numbers in the series to produce
        $Limit = 100

        if ($Limit -le 0) {
            throw "Cannot produce negative number of numbers"
        $n1 = 0;
        $n2 = 1;

        $i = 0;
        while ($i -lt $Limit) {
            if ($i -eq 0) {
                $n1 | Write-Output
            } elseif ($i -eq 1) {
                $n2 | Write-Output
            } else {
                $new = $n2 + $n1
                $n1 = $n2
                $n2 = $new
                $new | Write-Output
            $i += 1

Here, we have to special case the first and second times through the loop because there isn’t enough data to complete the next step. Once we do get beyond there, we can use the formula. For reference, the 100’th element is 2.18922995834555E+20 (a very large number) – the numbers escalate ridiculously quickly.