Learning Powershell – Recursive Fibonacci Computation


When learning a new programming language (scripting or general), it is always better to try something easy, simple at first. My recommendation is to implement the Fibonacci computation, which is known for the formula: F(n) = F(n – 1) + F(n – 2) where F(0) = 1 and F(1) = 1.

In powershell, you can define function using keyword function which is similar to other programming language.

function fib() { }

You can then declare a paramter $n (variables in Powershell start with dollar sign, which is similar to PHP).

function fib($n) {}

Alternatively, you can use the following syntax:

function fib() {
  param($n)
}

Powershell variables can have types, so you can explicitly define typed-variables:

function fib([int]$n) { }
# or
function fib() {
  param([int]$n)
}

The recursive implementation in Powershell for Fibonacci computation is:

// helloacm.com
function Fib($n) {
    switch ($n) {
        0 { 1; break }
        1 { 1; break }
        default {  # must use brackets (), similar to eval() in js
            (Fib($n - 1)) + (Fib($n - 2)) 
        }
    }
}

Here, we use a switch to test multiple situations. The return keyword can be omitted in Powershell if there is no following code to be executed after. The return terminates the execution of the current function, and you can also use exit to end the function.

If you use if, it will be something like this:

// helloacm.com
function Fib($n) {
    if ($n -eq 1 -or $n -eq 0) { return 1 }
    (Fib($n - 1)) + (Fib($n - 2)) # must use brackets (), similar to eval() in js
}

We use -eq to test for equality, the -or for logic or so other comparisons are similar (you know this style now).

If implemented in iterative format, we need the for loop, which is made C-like in Powershell.

// helloacm.com
function Fib() {
    param ($n)
    $a = 0
    $b = 1
    for ($i = 1; $i -le $n; $i ++) {
        $c = $a + $b
        $a = $b
        $b = $c
    }
    $c
}

The for can be also replaced by this kind of style:

foreach ($i in 1..$n) {

}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
403 words
Last Post: Simple Math Exercise - Computer V.S. Human
Next Post: HTML Hyper Link in New Windows by XHTML 1.0 standard

The Permanent URL is: Learning Powershell – Recursive Fibonacci Computation

Leave a Reply