Friday, September 2, 2016

Factorial and Fibonacci in PowerShell



Here below a little program in PowerShell that implements 2 classes. There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its methods are not static. And finally the script part that instantiates and executes the script program.

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members, and finally the third one that uses different return types (including System.Numerics.BigInteger) for the Factorial method to compare the timing and result.

As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html 


The Fiborial Program

# Factorial and Fibonacci in PowerShell 
Add-Type -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Numerics.dll"

# Instance Class (No static modifier at class level)
class StaticFiborial {
    # Static Field  
    hidden static [String] $className
    # Static Constructor  
    static StaticFiborial() {  
        [StaticFiborial]::className = "Static Constructor"
        Write-Host ([StaticFiborial]::className)
    }  
    # Static Method - Factorial Recursive  
    static [System.Numerics.BigInteger] FactorialR([Int] $n) {  
        if ($n -eq 1) {
            return 1 #[System.Numerics.BigInteger]::One  
        } else {
            return $n * [StaticFiborial]::FactorialR($n - 1)
        }
    }
    # Static Method - Factorial Imperative   
    static [System.Numerics.BigInteger] FactorialI([Int] $n) {
        $res = [System.Numerics.BigInteger]::One
        for($i = $n
            $i -ge 1
            $i--) {
            #$res = [System.Numerics.BigInteger]::Multiply($res, [System.Numerics.BigInteger]::new($i))
            $res *= $i
        }        
        return $res
    }
    # Static Method - Fibonacci Recursive  
    static [System.Numerics.BigInteger] FibonacciR([Int] $n) {  
        if ($n -lt 2) {
            return 1 #[System.Numerics.BigInteger]::One  
        } else {            
            return [StaticFiborial]::FibonacciR($n - 1) + [StaticFiborial]::FibonacciR($n - 2)
        }
    }
    # Static Method - Fibonacci Imperative  
    static [System.Numerics.BigInteger] FibonacciI([Int] $n) {  
        [long] $pre = 1
        [long] $cur = 1
        [long] $tmp = 0
        for ($i = 2; $i -le $n; $i++) {  
            $tmp = $cur + $pre
            $pre = $cur  
            $cur = $tmp  
        }  
        return $cur 
    }
    # Static Method - Benchmarking Algorithms 
    static [void] BenchmarkAlgorithm([Int] $algorithm, [int[]] $values) {
        $timer = [System.Diagnostics.Stopwatch]::new()
        $i = 0
        $testValue = 0
        $facTimeResult = [System.Numerics.BigInteger]::Zero
        $fibTimeResult = 0

        # "Switch" Flow Constrol Statement          
        switch ($algorithm) {          
            1 {
                Write-Host "`nFactorial Imperative:"
                # "For" Loop Statement
                for($i = 0; $i -lt $values.Length; $i++) {
                    $testValue = $values[$i]
                    # Taking Time   
                    $timer.Start()
                    $facTimeResult = [StaticFiborial]::FactorialI($testValue)
                    $timer.Stop()
                    # Getting Time    
                    Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
                }                
            }
            2 {
                Write-Host "`nFactorial Recursive:"      
                # "While" Loop Statement          
                while ($i -lt $values.Length) { 
                    $testValue = $values[$i]
                    # Taking Time   
                    $timer.Start()
                    $facTimeResult = [StaticFiborial]::FactorialR($testValue)
                    $timer.Stop()
                    # Getting Time    
                    Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
                    $i++                
                }                          
            }
            3 {
                Write-Host "`nFibonacci Imperative:"      
                # "Do-While" Loop Statement           
                do {
                    $testValue = $values[$i]
                    # Taking Time   
                    $timer.Start()
                    $fibTimeResult = [StaticFiborial]::FibonacciI($testValue)
                    $timer.Stop()
                    # Getting Time    
                    Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
                    $i++                
                } while ($i -lt $values.Length)                       
            }
            4 {
                Write-Host "`nFibonacci Recursive:"
                # "For" Loop Statement
                foreach ($testValue in $values) {                    
                    # Taking Time   
                    $timer.Start()
                    $fibTimeResult = [StaticFiborial]::FibonacciR($testValue)
                    $timer.Stop()
                    # Getting Time    
                    Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
                }                
            }
            default {   
                echo "DONG!`n"                
            }
        }
    }
}


# Instance Class
class InstanceFiborial {
    # Instance Field
    hidden [string] $className
    # Instance Constructor
    InstanceFiborial() {
        $this.className = "Instance Constructor"
        Write-Host $this.className
    }
    # Instance Method - Factorial Recursive
    [System.Numerics.BigInteger] FactorialR([int] $n) {
        # Calling Static Method
        return [StaticFiborial]::FactorialR($n)
    }
    # Instance Method - Factorial Imperative
    [System.Numerics.BigInteger] FactorialI([int] $n) {
        # Calling Static Method
        return [StaticFiborial]::FactorialI($n)
    }
    # Instance Method - Fibonacci Recursive
    [long] FibonacciR([int] $n) {
        # Calling Static Method
        return [StaticFiborial]::FibonacciR($n)
    }
    # Instance Method - Factorial Imperative
    [long] FibonacciI([int] $n) {
        # Calling Static Method
        return [StaticFiborial]::FibonacciI($n)
    }
}


Write-Host "`nInstance Class (with static methods)"
# Calling Static Methods
# Instantiation needed. Calling method directly from the class

Write-Host ("FacImp(5) = {0}" -f [StaticFiborial]::FactorialI(5))
Write-Host ("FacRec(5) = {0}" -f [StaticFiborial]::FactorialR(5))
Write-Host ("FibImp(11)= {0}" -f [StaticFiborial]::FibonacciI(11))
Write-Host ("FibRec(11)= {0}" -f [StaticFiborial]::FibonacciR(11))

Write-Host "`nInstance Class"
# Calling Instance Class and Methods 
# Need to instantiate before using. Calling method from instantiated object

$ff = [InstanceFiborial]::new()
# or
# $ff = New-Object InstanceFiborial

Write-Host ("FacImp(5) = {0}" -f $ff.FactorialI(5))
Write-Host ("FacRec(5) = {0}" -f $ff.FactorialR(5))
Write-Host ("FibImp(11)= {0}" -f $ff.FibonacciI(11))
Write-Host ("FibRec(11)= {0}" -f $ff.FibonacciR(11))


# Create a (generic) list of integer values to test
# From 5 to 50 by 5
$values = @()
for($i = 5; $i -le 50; $i += 5) {
    $values += $i
}

# Benchmarking Fibonacci                     
# 1 = Factorial Imperative            
[StaticFiborial]::BenchmarkAlgorithm(1, $values)
# 2 = Factorial Recursive
[StaticFiborial]::BenchmarkAlgorithm(2, $values) 

# Benchmarking Factorial            
# 3 = Fibonacci Imperative
[StaticFiborial]::BenchmarkAlgorithm(3, $values)
# 4 = Fibonacci Recursive
[StaticFiborial]::BenchmarkAlgorithm(4, $values)

# Stop and Exit
Read-Host 


And the Output is:














































Printing the Factorial and Fibonacci Series
Add-Type -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Numerics.dll"

class Fiborial {

    # Using a StringBuilder as a list of string elements
    static [String] GetFactorialSeries([int] $n) {
        # Create the String that will hold the list
        $series = [System.Text.StringBuilder]::new()
        # We begin by concatenating the number you want to calculate
        # in the following format: "!# ="
        [void]$series.Append("!")
        [void]$series.Append($n)
        [void]$series.Append(" = ")
        # We iterate backwards through the elements of the series
        for($i = $n; $i -le $n -and $i -gt 0; $i--) {        
            # and append it to the list
            [void]$series.Append($i)
            if ($i -gt 1) {
                [void]$series.Append(" * ")
            }
            else {
                [void]$series.Append(" = ") 
            }
        }
        # Get the result from the Factorial Method
        # and append it to the end of the list
        [void]$series.Append([Fiborial]::Factorial($n))
        # return the list as a string        

        return $series.ToString()
    }

    # Using a StringBuilder as a list of string elements
    static [String] GetFibonnaciSeries([int] $n) {
        # Create the String that will hold the list
        $series = New-Object -TypeName "System.Text.StringBuilder"
        # We begin by concatenating the first 3 values which
        # are always constant
        [void]$series.Append("0, 1, 1")
        # Then we calculate the Fibonacci of each element
        # and add append it to the list
        for ($i = 2
             $i -le $n
             $i++) {
            if ($i -lt $n) {
                [void]$series.Append(", ")
            }
            else {
                [void]$series.Append(" = ")
            }
                
            [void]$series.Append([Fiborial]::Fibonacci($i))
        }
        # return the list as a string
        return $series.ToString()
    }

    static [System.Numerics.BigInteger] Factorial([Int] $n) {  
        if ($n -eq 1) {
            return [System.Numerics.BigInteger]::One  
        } else {
            return $n * [Fiborial]::Factorial($n - 1)
        }
    }

    static [System.Numerics.BigInteger] Fibonacci([Int] $n) {  
        if ($n -lt 2) {
            return [System.Numerics.BigInteger]::One  
        } else {            
            return [Fiborial]::Fibonacci($n - 1) + [Fiborial]::Fibonacci($n - 2)
        }
    }
}


echo ("Printing Factorial Series")
echo ([Fiborial]::GetFactorialSeries(5))
echo ([Fiborial]::GetFactorialSeries(7))
echo ([Fiborial]::GetFactorialSeries(9))
echo ([Fiborial]::GetFactorialSeries(11))
echo ([Fiborial]::GetFactorialSeries(40))

Write-Host  ("Printing Fibonacci Series")
Write-Host  ([Fiborial]::GetFibonnaciSeries(5))
Write-Host  ([Fiborial]::GetFibonnaciSeries(7))
Write-Host  ([Fiborial]::GetFibonnaciSeries(9))
Write-Host  ([Fiborial]::GetFibonnaciSeries(11))
Write-Host  ([Fiborial]::GetFibonnaciSeries(40))

And the Output is:

















Mixing Instance and Static Members in the same Class

Instance classes can contain both, instance and static members such as: fields, constructors, methods, etc.

   
Add-Type -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Numerics.dll"

# Instance Class  
class Fiborial {

    # Instance Field  
    hidden [int] $instanceCount  
    # Static Field  
    hidden static [int] $staticCount          
    # Instance Read-Only Property/Getter  
    # Within instance members, you can always use    
    # the "this" reference pointer to access your (instance) members.  
    [int] GetInstanceCount() {  
        return $this.instanceCount
    }  
    # Static Read-Only Property/Getter  
    # As with Static Methods, you cannot reference your class members  
    # with the "this" reference pointer since static members are not  
    # instantiated.
    static [int] GetStaticCount() {  
        return [Fiborial]::staticCount
    }  
    # Instance Constructor 
    Fiborial() {    
        $this.instanceCount = 0
        Write-Host ("Instance Constructor $($this.instanceCount)`n")
    }    
    # Static Constructor  
    static Fiborial() {
        [Fiborial]::staticCount = 0
        Write-Host ("Static Constructor $([Fiborial]::staticCount)`n")
    }
    # Instance Method  
    [void] Factorial([int] $n)  
    {    
        $this.instanceCount++  
        Write-Host ("Factorial($n)`n") 
    }  
    # Static Method  
    static [void] Fibonacci([int] $n)   
    {      
        [Fiborial]::staticCount++
        Write-Host ("Fibonacci($n)`n")  
    }      
}

# Calling Static Constructor/Initializer and Methods  
# No need to instantiate  
[Fiborial]::Fibonacci(5)              
  
# Calling Instance Constructor and Methods  
# Instance required  
$fib = [Fiborial]::new()
$fib.Factorial(5)  

[Fiborial]::Fibonacci(15)              
$fib.Factorial(5)  

# Calling Instance Constructor and Methods  
# for a second object  
$fib2 = [Fiborial]::new()  
$fib2.Factorial(5)

# Calling Static Method  
Write-Host ("Static Count = $([Fiborial]::GetStaticCount())")  
# Calling Instance Property of object 1 and 2  
Write-Host ("Instance 1 Count = $($fib.GetInstanceCount())")
Write-Host ("Instance 2 Count = $($fib2.GetInstanceCount())")  
  
Read-Host 


And the Output is:


















Factorial using System.Int64, System.Double, System.Numerics.BigInteger

The Factorial of numbers over 20 are massive!
For instance: !40 = 815915283247897734345611269596115894272000000000!
Because of this, the previous version of this program was giving the "wrong" result
!40 = -70609262346240000 when using "long" (System.Int64) type, but it was not until I did the Fiborial version in VB.NET that I realized about this faulty code, because instead of giving me a wrong value, VB.NET, JScript.NET, Boo execution thrown an Overflow Exception when using the "Long/long" (System.Int64) type.

My first idea was to use ulong and ULong, but both failed for "big" numbers. I then used Double (double floating point) type and got no more exception/wrong result. The result of the factorial was now correct !40 = 1.1962222086548E+56, but still I wanted to show the Integer value of it, so I did some research and found that there is a new System.Numerics.BigInteger class in the .NET Framework 4.0. Adding the reference to the project and using this new class as the return type of the Factorial methods, I was able to get the result I was expecting.
!40 = 815915283247897734345611269596115894272000000000

What I also found was that using different types change the time the algorithm takes to finish:
System.Int64 < System.Double < System.Numerics.BigInteger
Almost by double!

To illustrate what I just said, lets have a look at the following code and the output we get.



NOTE: you need to manually add a reference to the System.Numerics.dll assembly to your project so you can add it to your code.

And the Output is:




























































No comments:

Post a Comment