Sunday, May 15, 2011

Stopwatch class for Java



In order to continue with my next "Factorial and Fibonacci" posts in some Java/JVM languages; I was looking for an official Java version of the .NET Timer class "Stopwatch" (System.Diagnostics.Stopwatch), so I can measure and display the elapsed time results in the same way I had been doing it in my previous posts.

Let's show some C# code of what I meant before continuing.

using System;
using System.Numerics;
using System.Diagnostics;

namespace CSStopwatchApp
{
    class StopwatchApp
    {
        static void Main(string[] args)
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();
            Fibonacci(50);
            timer.Stop();

            Console.WriteLine("Elapsed time in ticks: {0}", 
                timer.Elapsed.Ticks);
            Console.WriteLine("Elapsed time in milliseconds: {0}", 
                timer.Elapsed.Milliseconds);
            Console.WriteLine("Elapsed time in seconds: {0}", 
                timer.Elapsed.Seconds);
            Console.WriteLine("Elapsed time in minutes: {0}", 
                timer.Elapsed.Minutes);
            Console.WriteLine("Elapsed time in hours: {0}", 
                timer.Elapsed.Hours);
            Console.WriteLine("Elapsed time with format: {0}", 
                timer.Elapsed);
        }
                
        private static BigInteger Fibonacci(int n)
        {
            if (n < 2)
                return 1;
            else
                return Fibonacci(n - 1) + Fibonacci(n - 2);
        }
    }
}

And the result:









However, looks like there isn't one, instead, there are 2 methods used to measure time in Java: System.nanoTime() and System.currentTimeMillis() being the first one more precise when timing code execution.


currentTimeMillis
public static long currentTimeMillis()
Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

For example, to measure how long some code takes to execute:
long startTime = System.currentTimeMillis();
   // ... the code being measured ...
   long estimatedTime = System.currentTimeMillis() - startTime;

Returns:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

nanoTime
public static long nanoTime()
Returns the current value of the most precise available system timer, in nanoseconds.

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

For example, to measure how long some code takes to execute:
long startTime = System.nanoTime();
   // ... the code being measured ...
   long estimatedTime = System.nanoTime() - startTime;
 

Returns:
The current value of the system timer, in nanoseconds.


So, I decided to do my own version of the Stopwatch class, not before doing some google to see if someone did it already ;) you know, code reuse FTW!

Quickly I found a basic version using System.currentTimeMillis() written by Corey Goldberg and provided with a GPL license here: http://www.goldb.org/stopwatchjava.html (thanks man!), so I took it and extended it to use System.nanoTime() instead, and implemented some other missing methods and the most important (for me) the Elapsed time formatted as "hh:mm:ss.sss" using the SimpleDateFormat class, which looks like only considers 3 milliseconds... so I added the rest (the nanoseconds part) to have: 00:00:00.0000000 (hh:mm:ss.sssssss), just like the .NET version output it. Here it is:

Stopwatch class in Java

/*
 *  Copyright (c) 2011, Carlos Quintanilla
 *  Special thanks to Corey Goldberg (for his StopWatch.java | Java Timer Class)
 *  here http://www.goldb.org/stopwatchjava.html
 * 
 *  Stopwatch.java is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 */

package stopwatchapp;

import java.text.SimpleDateFormat;
import java.util.Calendar;  

/**
 * @author Carlos Quintanilla
 */

public class Stopwatch {
    // constants
    private final long nsPerTick = 100;
    private final long nsPerMs = 1000000;
    private final long nsPerSs = 1000000000;
    private final long nsPerMm = 60000000000L;
    private final long nsPerHh = 3600000000000L;

    private long startTime = 0;
    private long stopTime = 0;
    private boolean running = false;
    
    /**
     * Starts measuring elapsed time
     * for an interval.
     */
    public void start() {
        this.startTime = System.nanoTime();       
        this.running = true;
    }
    
    /**
     * Stops measuring elapsed time
     * for an interval.
     */
    public void stop() {
        this.stopTime = System.nanoTime();
        this.running = false;
    }
    
    /**
     * Stops time interval measurement 
     * and resets the elapsed time to zero.
     */ 
    public void reset() {
        this.startTime = 0;
        this.stopTime = 0;
        this.running = false;
    }
    
    /**
     * Gets the total elapsed time measured 
     * by the current instance, in nanoseconds.
     * 1 Tick = 100 nanoseconds 
     */
    public long getElapsedTicks() {
        long elapsed;
        if (running) {
             elapsed = (System.nanoTime() - startTime);
        }
        else {
            elapsed = (stopTime - startTime);
        }
        return elapsed / nsPerTick;
    }
    
    /**
     * Gets the total elapsed time measured 
     * by the current instance, in milliseconds.
     * 10000 Ticks = 1 millisecond (1000000 nanoseconds)
     */
    public long getElapsedMilliseconds() {
        long elapsed;
        if (running) {
             elapsed = (System.nanoTime() - startTime);
        }
        else {
            elapsed = (stopTime - startTime);
        }
        return elapsed / nsPerMs;
    }
    
    /**
     * Gets the total elapsed time measured 
     * by the current instance, in seconds.
     * 10000000 Ticks = 1 second (1000 milliseconds)
     */
    public long getElapsedSeconds() {
        long elapsed;
        if (running) {
             elapsed = (System.nanoTime() - startTime);
        }
        else {
            elapsed = (stopTime - startTime);
        }        
        return elapsed / nsPerSs;
    }
    
    /**
     * Gets the total elapsed time measured 
     * by the current instance, in minutes.
     * 600000000 Ticks = 1 minute (60 seconds)
     */
    public long getElapsedMinutes() {
        long elapsed;
        if (running) {
             elapsed = (System.nanoTime() - startTime);
        }
        else {
            elapsed = (stopTime - startTime);
        }        
        return elapsed / nsPerMm;
    }
    
    /**
     * Gets the total elapsed time measured 
     * by the current instance, in hours.
     * 36000000000 Ticks = 1 hour (60 minutes)
     */
    public long getElapsedHours() {
        long elapsed;
        if (running) {
             elapsed = (System.nanoTime() - startTime);
        }
        else {
            elapsed = (stopTime - startTime);
        }        
        return elapsed / nsPerHh;
    }
    
    /**
     * Gets the total elapsed time with format 
     * 00:00:00.0000000 = 00:mm:ss.SSS + 9999 Ticks
     */ 
    public String getElapsed() {
        String timeFormatted = "";
        timeFormatted = this.formatTime(this.getElapsedTicks());        
        return timeFormatted;
    }
    
    /**
     * Gets the total elapsed time with format 
     * 00:00:00.0000000 = 00:mm:ss.SSS + #### Ticks
     * @param elapsedTicks elapsed ticks between start and stop nano time
     */ 
    private String formatTime(final long elapsedTicks) {        
        String formattedTime = "";
        // should be hh:mm:ss.SSS, but 00 starts with 01 
        SimpleDateFormat formatter = new SimpleDateFormat("00:mm:ss.SSS");
        Calendar calendar = Calendar.getInstance();        
        
        if (elapsedTicks <= 9999) {
            calendar.setTimeInMillis(0);
            formattedTime = formatter.format(calendar.getTime()) 
                    + String.valueOf(String.format("%04d", elapsedTicks));
        }
        else {
            calendar.setTimeInMillis(elapsedTicks * nsPerTick / nsPerMs);            
            String formattedTicks = String.format("%07d", elapsedTicks);
            formattedTicks = formattedTicks.substring(formattedTicks.length() - 4);
            formattedTime = formatter.format(calendar.getTime()) + formattedTicks;
        }
        return formattedTime;
    }
}


If we add that class in any Java project, we can now do what the C# code at the beginning of this post does! Let's see the Java version of the code:

package stopwatchapp;
import java.math.BigInteger;

public class StopwatchApp {

    public static void main(String[] args) {
        
        Stopwatch timer = new Stopwatch();
        timer.start();
        Fibonacci(50);
        timer.stop();
        
        System.out.println("Elapsed time in ticks: " 
            + timer.getElapsedTicks());
        System.out.println("Elapsed time in milliseconds: " 
            + timer.getElapsedMilliseconds());
        System.out.println("Elapsed time in seconds: " 
            + timer.getElapsedSeconds());
        System.out.println("Elapsed time in minutes: " 
            + timer.getElapsedMinutes());
        System.out.println("Elapsed time in hours: " 
            + timer.getElapsedHours());
        System.out.println("Elapsed time with format: " 
            + timer.getElapsed());
    }
    
    private static BigInteger Fibonacci(int n)
    {
        if (n < 2)
            return BigInteger.ONE;
        else
            return Fibonacci(n - 1).add(Fibonacci(n - 2));
    }
}


And the Output is:















That's it! now I'm ready to work on the next posts using this java timer class. Hope it is helpful to you too since I found lot's of forums asking for it and the answer was always use: System.nanoTime() and System.currentTimeMillis()

By the way, if you want to run the example, change Fibonacci(50) to a lower value such as Fibonacci(35 or 40) to not wait for the result some minutes.

Factorial and Fibonacci in Java



Here below a little program in Java that implements 2 classes (in fact, they are 3 + an extra utility Stopwatch class from my previous post http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html). 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 there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "main".

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 java.math.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 Java
package fiborial;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

// Instance Class         
// static is not a class modifier in Java
public class StaticFiborial
{  
    // Static Field  
    private static String className;  
    // Static Constructor/Initializer
    static
    {  
        className = "Static Constructor";  
        System.out.println(className);        
    }  
    // Static Method - Factorial Recursive  
    public static BigInteger factorialR(int n)  
    {  
        if (n == 1)  
            return BigInteger.ONE;
        else  
            return BigInteger.valueOf(n).multiply(factorialR(n - 1));
    }  
    // Static Method - Factorial Imperative  
    public static BigInteger factorialI(int n)  
    {  
        BigInteger res = BigInteger.ONE;  
        for (int i = n; i >= 1; i--)  
        {                  
            res = res.multiply(BigInteger.valueOf(i));  
        }  
        return res;
    }  
    // Static Method - Fibonacci Recursive  
    public static long fibonacciR(int n)  
    {  
        if (n < 2)  
            return 1;  
        else  
            return fibonacciR(n - 1) + fibonacciR(n - 2);  
    }  
    // Static Method - Fibonacci Imperative  
    public static long fibonacciI(int n)  
    {              
        long pre, cur, tmp = 0;  
        pre = cur = 1;              
        for (int i = 2; i <= n; i++)  
        {  
            tmp = cur + pre;  
            pre = cur;  
            cur = tmp;  
        }  
        return cur;  
    }      
    // Static Method - Benchmarking Algorithms  
    public static void benchmarkAlgorithm(int algorithm, List<Integer> values)  
    {              
        Stopwatch timer = new Stopwatch();  
        int i, testValue;  
        BigInteger facTimeResult = BigInteger.valueOf(0);  
        long fibTimeResult = 0;  
        i = testValue = 0;              
          
        // "Switch" Flow Control Statement  
        switch (algorithm)  
        {  
            case 1:  
                System.out.println("\nFactorial Imperative:");  
                // "For" Loop Statement  
                for (i = 0; i < values.size(); i++)  
                {                          
                    testValue = ((Integer)values.get(i)).intValue();  
                    // Taking Time  
                    timer.start();  
                    facTimeResult = factorialI(testValue);  
                    timer.stop();                          
                    // Getting Time  
                    System.out.println(" (" + testValue + ") = " 
                        + timer.getElapsed());  
                }                      
                break;  
            case 2:  
                System.out.println("\nFactorial Recursive:");  
                // "While" Loop Statement  
                while (i < values.size())  
                {                          
                    testValue = ((Integer)values.get(i)).intValue();  
                    // Taking Time  
                    timer.start();  
                    facTimeResult = factorialR(testValue);  
                    timer.stop();  
                    // Getting Time  
                    System.out.println(" (" + testValue + ") = " 
                        + timer.getElapsed());  
                    i++;  
                }  
                break;  
            case 3:  
                System.out.println("\nFibonacci Imperative:");  
                // "Do-While" Loop Statement  
                do {  
                    testValue = ((Integer)values.get(i)).intValue();  
                    // Taking Time  
                    timer.start();  
                    fibTimeResult = fibonacciI(testValue);  
                    timer.stop();  
                    // Getting Time  
                    System.out.println(" (" + testValue + ") = " 
                        + timer.getElapsed());  
                    i++;  
                } while (i < values.size());  
                break;  
            case 4:  
                System.out.println("\nFibonacci Recursive:");  
                // "For Each" Loop Statement  
                for (Integer item : values)  
                {  
                    testValue = item;  
                    // Taking Time  
                    timer.start();  
                    fibTimeResult = fibonacciR(testValue);  
                    timer.stop();  
                    // Getting Time  
                    System.out.println(" (" + testValue + ") = " 
                        + timer.getElapsed());  
                }  
                break;  
            default:  
                System.out.println("DONG!");  
                break;  
        }                  
    }  
}

package fiborial;
import java.math.BigInteger;
// Instance Class  
public class InstanceFiborial  
{  
    // Instance Field  
    private String className;  
    // Instance Constructor  
    public InstanceFiborial()  
    {  
        this.className = "Instance Constructor";  
        System.out.println(this.className);
    }  
    // Instance Method - Factorial Recursive  
    public BigInteger factorialR(int n)  
    {  
        // Calling Static Method  
        return StaticFiborial.factorialR(n);  
    }  
    // Instance Method - Factorial Imperative  
    public BigInteger factorialI(int n)  
    {  
        // Calling Static Method  
        return StaticFiborial.factorialI(n);  
    }  
    // Instance Method - Fibonacci Recursive  
    public long fibonacciR(int n)  
    {  
        // Calling Static Method  
        return StaticFiborial.fibonacciR(n);  
    }  
    // Instance Method - Factorial Imperative  
    public long fibonacciI(int n)  
    {  
        // Calling Static Method  
        return StaticFiborial.fibonacciI(n);  
    }  
}

package fiborial;
import java.util.Scanner; 
import java.util.ArrayList;
import java.util.List;

public class StaticFiborialProgram 
{
    public static void main(String[] args)
    {
        System.out.println("\nStatic Class");  
        // Calling Static Class and Methods  
        // No instantiation needed. Calling method directly from the class  
        System.out.println("FacImp(5) = " + StaticFiborial.factorialI(5));  
        System.out.println("FacRec(5) = " + StaticFiborial.factorialR(5));  
        System.out.println("FibImp(11)= " + StaticFiborial.fibonacciI(11));  
        System.out.println("FibRec(11)= " + StaticFiborial.fibonacciR(11));  

        System.out.println("\nInstance Class");  
        // Calling Instance Class and Methods   
        // Need to instantiate before using. Calling method from instantiated object  
        InstanceFiborial ff = new InstanceFiborial();  
        System.out.println("FacImp(5) = " + ff.factorialI(5));  
        System.out.println("FacRec(5) = " + ff.factorialR(5));  
        System.out.println("FibImp(11)= " + ff.fibonacciI(11));  
        System.out.println("FibRec(11)= " + ff.fibonacciR(11));  

        // Create a (generic) list of integer values to test  
        // From 5 to 50 by 5  
        List<Integer> values = new ArrayList<Integer>();  
        for(int i = 5; i <= 50; i += 5)  
            values.add(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  
        System.out.println("Press any key to exit...");  
        Scanner in = new Scanner(System.in);  
        String line = in.nextLine();  
        in.close();  
    }
}

And the Output is:




Printing the Factorial and Fibonacci Series
package fiborialseries;
import java.math.BigInteger;
import java.lang.StringBuffer;

class Fiborial
{
    // Using a StringBuffer as a list of string elements
    public static String getFactorialSeries(int n)
    {
        // Create the String that will hold the list
        StringBuffer series = new StringBuffer();
        // We begin by concatenating the number you want to calculate
        // in the following format: "!# ="
        series.append("!");
        series.append(n);
        series.append(" = ");
        // We iterate backwards through the elements of the series
        for (int i = n; i <= n && i > 0; i--)
        {
            // and append it to the list
            series.append(i);
            if (i > 1)
                series.append(" * ");
            else 
                series.append(" = "); 
        }
        // Get the result from the Factorial Method
        // and append it to the end of the list
        series.append(factorial(n));
        // return the list as a string
        return series.toString();
    }

    // Using a StringBuffer as a list of string elements
    public static String getFibonnaciSeries(int n)
    {
        // Create the String that will hold the list
        StringBuffer series = new StringBuffer();
        // We begin by concatenating the first 3 values which
        // are always constant
        series.append("0, 1, 1");
        // Then we calculate the Fibonacci of each element
        // and add append it to the list
        for (int i = 2; i <= n; i++)
        {
            if (i < n)
                series.append(", ");
            else
                series.append(" = ");
            
            series.append(fibonacci(i));
        }
        // return the list as a string
        return series.toString();
    }

    public static BigInteger factorial(int n)
    {
        if (n == 1)  
            return BigInteger.ONE;
        else  
            return BigInteger.valueOf(n).multiply(factorial(n - 1));
    }        

    public static long fibonacci(int n)
    {
        if (n < 2)  
            return 1;  
        else  
            return fibonacci(n - 1) + fibonacci(n - 2);  
    }   
}

package fiborialseries;

class FiborialExtrasProgram
{    
    public static void main(String[] args) 
    {            
        // Printing Factorial Series
        System.out.println("");
        System.out.println(Fiborial.getFactorialSeries(5));
        System.out.println(Fiborial.getFactorialSeries(7));
        System.out.println(Fiborial.getFactorialSeries(9));
        System.out.println(Fiborial.getFactorialSeries(11));
        System.out.println(Fiborial.getFactorialSeries(40));
        // Printing Fibonacci Series
        System.out.println("");
        System.out.println(Fiborial.getFibonnaciSeries(5));
        System.out.println(Fiborial.getFibonnaciSeries(7));
        System.out.println(Fiborial.getFibonnaciSeries(9));
        System.out.println(Fiborial.getFibonnaciSeries(11));
        System.out.println(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, getters/setters, constructors/initializers, methods, etc.

package fiborialextrasjava2;

// Instance Class  
class Fiborial  
{  
    // Instance Field  
    private int instanceCount;  
    // Static Field  
    private static int staticCount;          
    // Instance Read-Only Getter  
    // Within instance members, you can always use    
    // the "this" reference pointer to access your (instance) members.  
    public int getInstanceCount()
    {  
        return this.instanceCount;   
    }  
    // Static Read-Only Getter      
    // As with Static Methods, you cannot reference your class members  
    // with the "this" reference pointer since static members are not  
    // instantiated.          
    public static int getStaticCount()
    {  
        return staticCount;  
    }  
    // Instance Constructor  
    public Fiborial()  
    {  
        this.instanceCount = 0;  
        System.out.println("\nInstance Constructor " + this.instanceCount); 
    }  
    // Static Constructor  
    static
    {  
        staticCount = 0;  
        System.out.println("\nStatic Constructor " + staticCount);  
    }  

    // Instance Method  
    public void factorial(int n)  
    {  
        this.instanceCount += 1;  
        System.out.println("\nFactorial(" + n + ")");  
    }  

    // Static Method  
    public static void fibonacci(int n)  
    {  
        staticCount += 1;  
        System.out.println("\nFibonacci(" + n + ")");  
    }                  
}

package fiborialextrasjava2;

class FiborialExtras2Program
{    
    public static void main(String[] args) 
    {            
        // Calling Static Constructor and Methods  
        // No need to instantiate  
        Fiborial.fibonacci(5);              

        // Calling Instance Constructor and Methods  
        // Instance required  
        Fiborial fib = new Fiborial();  
        fib.factorial(5);              

        Fiborial.fibonacci(15);              
        fib.factorial(5);  

        // Calling Instance Constructor and Methods  
        // for a second object  
        Fiborial fib2 = new Fiborial();  
        fib2.factorial(5);  
          
        System.out.println("");
        // Calling Static Property  
        System.out.println("Static Count = " + Fiborial.getStaticCount());  
        // Calling Instance Property of object 1 and 2  
        System.out.println("Instance 1 Count = " + fib.getInstanceCount());  
        System.out.println("Instance 2 Count = " + fib2.getInstanceCount());          
    }
}

And the Output is:























Factorial using java.lang.Long, java.lang.Double, java.math.BigInteger


package fiborialextrasjava3;
import java.math.BigInteger;

class FiborialExtrasProgram
{    
    public static void main(String[] args) 
    {            
        Stopwatch timer = new Stopwatch();  
        long facIntResult = 0;  
        double facDblResult = 0;  
        BigInteger facBigResult = BigInteger.valueOf(0);  

        System.out.println("\nFactorial using Int64");
        // Benchmark Factorial using Int64  
        for (int i = 5; i <= 50; i += 5)  
        {  
            timer.start();  
            facIntResult = factorialInt64(i);  
            timer.stop();  
            System.out.println(" (" + i + ") = " 
                + timer.getElapsed() + " : " + facIntResult);
        }  
        System.out.println("\nFactorial using Double");  
        // Benchmark Factorial using Double  
        for (int i = 5; i <= 50; i += 5)  
        {  
            timer.start();  
            facDblResult = factorialDouble(i);  
            timer.stop();              
            System.out.println(" (" + i + ") = " 
                + timer.getElapsed() + " : " + facDblResult);
        }  
        System.out.println("\nFactorial using BigInteger");  
        // Benchmark Factorial using BigInteger  
        for (int i = 5; i <= 50; i += 5)  
        {  
            timer.start();  
            facBigResult = factorialBigInteger(i);  
            timer.stop();  
            System.out.println(" (" + i + ") = " 
                + timer.getElapsed() + " : " + facBigResult);
        }          
    }
    
    // Long Factorial  
    public static long factorialInt64(int n)  
    {  
        if (n == 1)  
            return 1;
        else  
            return n * factorialInt64(n - 1);
    }
    
    // Double Factorial
    public static double factorialDouble(int n)  
    {  
        if (n == 1)  
            return 1;
        else  
            return n * factorialDouble(n - 1);
    }
    
    // BigInteger Factorial 
    public static BigInteger factorialBigInteger(int n)  
    {  
        if (n == 1)  
            return BigInteger.ONE;
        else  
            return BigInteger.valueOf(n).multiply(factorialBigInteger(n - 1));
    }
}



And the Output is:

Sunday, April 3, 2011

Factorial and Fibonacci in Phalanger



Update 1: using BigInteger Multiply method instead of unsupported custom * Operator.
Update 2: Porting code examples to Phalanger 3 - syntax changes on namespace use.

Here below a little program in Phalanger that implements 2 classes (in fact, they are 3). 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 there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "Main".

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

<?php      
# Factorial and Fibonacci in Phalanger        
namespace FiborialPhp;

use System;
use System\Collections\Generic as G;
use System\Diagnostics as D;
use System\Numerics as N;

# Instance Class           
# static is not a class modifier in PHP    
[\Export]
class StaticFiborial    
{      
    # Static Field     
    private static $className;    
    # no available static __constructor support    
    # Static Initializer Method instead, but need to be explicitly invoked    
    public static function StaticFiborialConstructor()    
    {                
        $className = "Static Constructor";    
        echo $className . "\n";    
    }            
    # Static Method - Factorial Recursive    
    public static function FactorialR(int $n)    
    {      
        if($n == 1)     
            return N\BigInteger::$One;  
        else                    
            return N\BigInteger::Multiply(new N\BigInteger($n), self::FactorialR($n-1));  
    }            
    # Static Method - Factorial Imperative        
    public static function FactorialI(int $n)     
    {                    
        $res = N\BigInteger::$One;
        for ($i = $n; $i >= 1; $i--)  
            $res = N\BigInteger::Multiply($res, new N\BigInteger($i));                  
        return $res;    
    }       
    # Static Method - Fibonacci Recursive        
    public static function FibonacciR(int $n)     
    {        
        if ($n < 2)    
            return 1;        
        else        
            return self::FibonacciR($n - 1) + self::FibonacciR($n - 2);        
    }    
    # Static Method - Fibonacci Imperative        
    public static function FibonacciI(int $n)     
    {    
        $pre = 0; $cur = 0; $tmp = 0;    
        $pre = 1; $cur = 1;    
        for ($i = 2; $i <= $n; $i++)     
        {    
            $tmp = $cur + $pre;        
            $pre = $cur;        
            $cur = $tmp;        
        }        
        return $cur;    
    }    
    # Static Method - Benchmarking Algorithms        
    public static function BenchmarkAlgorithm(int $algorithm, G\List<:int:> $values)     
    {    
        $timer = new D\Stopwatch();    
        $i = 0;     
        $testValue = 0;                
        $facTimeResult = N\BigInteger::$Zero;  
        $fibTimeResult = 0;        
                
        # "Switch" Flow Constrol Statement        
        switch ($algorithm)        
        {        
            case 1:        
                echo "\nFactorial Imperative:\n";    
                # "For" Loop Statement        
                for ($i = 0; $i < $values->Count; $i++)      
                {                                                    
                    $testValue = $values->get_Item($i);    
                    # Taking Time        
                    $timer->Start();        
                    $facTimeResult = self::FactorialI($testValue);        
                    $timer->Stop();                                
                    # Getting Time                              
                    echo " ($testValue) = {$timer->Elapsed->ToString()}\n";    
                }                            
                break;        
            case 2:        
                echo "\nFactorial Recursive:\n";    
                # "While" Loop Statement        
                while ($i < $values->Count)        
                {                                
                    $testValue = $values->get_Item($i);                            
                    # Taking Time        
                    $timer->Start();        
                    $facTimeResult = self::FactorialR($testValue);        
                    $timer->Stop();        
                    # Getting Time        
                    echo " ($testValue) = {$timer->Elapsed->ToString()}\n";    
                    $i++;    
                }    
                break;        
            case 3:        
                echo "\nFibonacci Imperative:\n";    
                # "Do-While" Loop Statement        
                do     
                {        
                    $testValue = $values->get_Item($i);    
                    # Taking Time        
                    $timer->Start();        
                    $fibTimeResult = self::FibonacciI($testValue);        
                    $timer->Stop();        
                    # Getting Time        
                    echo " ($testValue) = {$timer->Elapsed->ToString()}\n";    
                    $i++;        
                } while ($i < $values->Count);                            
                break;        
            case 4:        
                echo "\nFibonacci Recursive:\n";    
                # "ForEach" Loop Statement        
                foreach ($values as $item)        
                {        
                    $testValue = (int)$item;        
                    # Taking Time        
                    $timer->Start();        
                    $fibTimeResult = self::FibonacciR($testValue);    
                    $timer->Stop();        
                    # Getting Time        
                    echo " ($testValue) = {$timer->Elapsed->ToString()}\n";    
                }        
                break;        
            default:        
                echo "DONG!\n";    
                break;    
        }                        
    }        
}    
    
[\Export]     
# Instance Class    
class InstanceFiborial    
{      
    # Instance  Field     
    private $className;    
    # Instance Constructor                            
    function __construct()      
    {      
        $this->className = "Instance Constructor";    
        echo $this->className . "\n";    
    }    
    # Instance Method - Factorial Recursive    
    public function FactorialR(int $n)    
    {      
        # Calling Static Method    
        return StaticFiborial::FactorialR($n);    
    }    
    # Instance Method - Factorial Imperative        
    public function FactorialI(int $n)     
    {        
        # Calling Static Method    
        return StaticFiborial::FactorialI($n);    
    }       
    # Instance Method - Fibonacci Recursive        
    public function FibonacciR(int $n)     
    {        
        # Calling Static Method    
        return StaticFiborial::FibonacciR($n);    
    }    
    # Instance Method - Fibonacci Imperative        
    public function FibonacciI(int $n)     
    {    
        # Calling Static Method    
        return StaticFiborial::FibonacciI($n);    
    }    
}    
    
# Console Program      
class Program      
{      
    public static function Main()      
    {      
        # Static Initializer/Constructor for StaticFiborial Class     
        # explicitly called somewhere in your code ^_^    
        StaticFiborial::StaticFiborialConstructor();    
                
        echo "\nStatic Class\n";    
        # Calling Static Class and Methods      
        # No instantiation needed. Calling method directly from the class      
        echo "FacImp(5) = " . StaticFiborial::FactorialI(5)->ToString() . "\n";    
        echo "FacRec(5) = " . StaticFiborial::FactorialR(5)->ToString() . "\n";    
        echo "FibImp(11)= " . StaticFiborial::FibonacciI(11)->ToString() . "\n";    
        echo "FibRec(11)= " . StaticFiborial::FibonacciR(11)->ToString() . "\n";    
      
        echo "\nInstance Class\n";      
        # Calling Instance Class and Methods      
        # Need to instantiate before using. Calling method from instantiated object      
        $ff = new InstanceFiborial();    
        echo "FacImp(5) = {$ff->FactorialI(5)->ToString()}\n";    
        echo "FacRec(5) = {$ff->FactorialR(5)->ToString()}\n";    
        echo "FibImp(11)= {$ff->FibonacciI(11)->ToString()}\n";    
        echo "FibRec(11)= {$ff->FibonacciR(11)->ToString()}\n";    
                              
        # From 5 to 50 by 5    
        $values = new G\List<:int:>;    
        for($i = 5; $i <= 50; $i += 5)    
            $values->Add($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      
        echo "Press any key to exit...";      
        fgets(STDIN);
        return 0;      
    }      
}    
 
?>

And the Output is:




































Printing the Factorial and Fibonacci Series
<?php        
namespace FiborialSeries;
use System;
use System\Text as T;    
use System\Numerics as N;
      
[\Export]
class Fiborial    
{      
    # Using a StringBuilder as a list of string elements                
    static function GetFactorialSeries(int $n)     
    {            
        # Create the String that will hold the list        
        $series = new T\StringBuilder();        
        # We begin by concatenating the number you want to calculate        
        # in the following format: "!# ="        
        $series->Append("!");        
        $series->Append($n);        
        $series->Append(" = ");        
        # We iterate backwards through the elements of the series        
        for ($i = $n; $i <= $n && $i > 0; $i--)     
        {        
            # and append it to the list        
            $series->Append($i);    
            if ($i > 1)        
                $series->Append(" * ");        
            else         
                $series->Append(" = ");         
        }        
        # Get the result from the Factorial Method        
        # and append it to the end of the list                                        
        # $series->Append(self::Factorial($n)->ToString());    
        # BUT! that throws an exception with big numbers (> fact(30))    
        # Overflow ex "Value was either too large or too small for a Decimal."  
        # because I think it is a bug i used an ugly workaround which is  
        # using the "." in the return.  
        return $series->ToString() . self::Factorial($n)->ToString();  
    }        
        
    # Using a StringBuilder as a list of string elements        
    static function GetFibonnaciSeries(int $n)        
    {        
        # Create the String that will hold the list        
        $series = new T\StringBuilder();    
        # We begin by concatenating the first 3 values which        
        # are always constant        
        $series->Append("0, 1, 1");        
        # Then we calculate the Fibonacci of each element        
        # and add append it to the list        
        for ($i = 2; $i <= $n; $i++)        
        {        
            if ($i < $n)        
                $series->Append(", ");        
            else        
                $series->Append(" = ");        
            
            $series->Append(self::Fibonacci($i));    
        }        
        # return the list as a string        
        return $series->ToString();        
    }        
    
    static function Factorial(int $n)    
    {      
        if($n == 1)     
            return new N\BigInteger(1);  
        else                    
            return N\BigInteger::Multiply(new N\BigInteger($n), self::Factorial($n - 1));  
    }    
            
    static function Fibonacci(int $n)     
    {        
        if ($n < 2)    
            return 1;    
        else        
            return self::Fibonacci($n - 1) + self::Fibonacci($n - 2);        
    }        
}    
    
class Program      
{      
    public static function Main()      
    {      
        # Printing Factorial Series        
        echo "\n";    
        echo Fiborial::GetFactorialSeries(5) . "\n";    
        echo Fiborial::GetFactorialSeries(7) . "\n";    
        echo Fiborial::GetFactorialSeries(9) . "\n";    
        echo Fiborial::GetFactorialSeries(11) . "\n";    
        echo Fiborial::GetFactorialSeries(40) . "\n";      
        # Printing Fibonacci Series  
        echo "\n";    
        echo Fiborial::GetFibonnaciSeries(5) . "\n";    
        echo Fiborial::GetFibonnaciSeries(7) . "\n";    
        echo Fiborial::GetFibonnaciSeries(9) . "\n";    
        echo Fiborial::GetFibonnaciSeries(11) . "\n";    
        echo Fiborial::GetFibonnaciSeries(40) . "\n";    
                 
        fgets(STDIN);
        return 0;      
    }      
}    
?>

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, properties, constructors, methods, etc.

<?php    
namespace FiborialExtras2;
use System;

# Instance Class  
[\Export]       
class Fiborial  
{    
    # Instance Field  
    private $instanceCount;  
    # Static Field  
    private static $staticCount;          
    # Instance Read-Only Property/Getter  
    # Within instance members, you can always use    
    # the "this" reference pointer to access your (instance) members.  
    public function 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.          
    public static function getStaticCount()  
    {  
        return $staticCount;  
    }  
    # Instance Constructor            
    public function __construct()    
    {    
        $this->instanceCount = 0;  
        echo "\nInstance Constructor {$this->instanceCount}\n";  
    }    
    # Static Constructor  
    public static function FiborialStaticConstructor()  
    {  
        $staticCount = 0;  
        echo "\nStatic Constructor {$staticCount}\n";  
    }      
    # Instance Method  
    public function Factorial(int $n)  
    {    
        $this->instanceCount += 1;  
        echo "\nFactorial({$n})\n";  
    }  
    # Static Method  
    public static function Fibonacci(int $n)   
    {      
        $staticCount += 1;  
        echo "\nFibonacci({$n})\n";  
    }      
}  
  
class Program    
{    
    public static function Main()    
    {    
        # Calling Static Constructor/Initializer and Methods  
        # No need to instantiate  
        Fiborial::FiborialStaticConstructor();  
        Fiborial::Fibonacci(5);              
  
        // Calling Instance Constructor and Methods  
        // Instance required  
        $fib = new Fiborial();  
        $fib->Factorial(5);  
  
        Fiborial::Fibonacci(15);              
        $fib->Factorial(5);  
  
        // Calling Instance Constructor and Methods  
        // for a second object  
        $fib2 = new Fiborial();  
        $fib2->Factorial(5);  
              
        echo "\n";  
        // Calling Static Property  
        echo "Static Count = " . Fiborial::getStaticCount() . "\n";  
        // Calling Instance Property of object 1 and 2  
        echo "Instance 1 Count = {$fib->getInstanceCount()}\n";  
        echo "Instance 2 Count = {$fib2->getInstanceCount()}\n";  
  
        fgets(STDIN);    
        return 0;    
    }    
}  
?>

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 "tried" to say, lets have a look at the following code and the output we get.

<?php      
use System\Numerics as N;
use System\Diagnostics as D;      
    
function FactorialInt64(int $n)     
{        
    if ($n == 1)        
        return 1;        
    else        
        return $n * FactorialInt64($n - 1);        
}        
    
function FactorialDouble(int $n)     
{        
    if ($n == 1)        
        return (double)1;        
    else        
        return (double)($n * FactorialDouble($n - 1));    
}    
    
function FactorialBigInteger(int $n)     
{        
    if($n == 1)     
        return N\BigInteger::$One;  
    else                    
        return N\BigInteger::Multiply(new N\BigInteger($n), FactorialBigInteger($n - 1));  
}    
    
class Program    
{    
    public static function Main()      
    {      
            $timer = new D\Stopwatch();    
            $facIntResult = 0;        
            $facDblResult = (double)0;        
            $facBigResult = N\BigInteger::$Zero;     
    
            echo "\nFactorial using Int64\n";        
            // Benchmark Factorial using Int64        
            for ($i = 5; $i <= 50; $i += 5)        
            {        
                $timer->Start();        
                $facIntResult = FactorialInt64($i);        
                $timer->Stop();        
                echo " ({$i}) = {$timer->Elapsed->ToString()} : {$facIntResult}\n";    
            }                    
            echo "\nFactorial using Double\n";        
            // Benchmark Factorial using Double    
            for ($i = 5; $i <= 50; $i += 5)        
            {        
                $timer->Start();        
                $facDblResult = FactorialDouble($i);        
                $timer->Stop();        
                echo " ({$i}) = {$timer->Elapsed->ToString()} : {$facDblResult}\n";    
            }        
            echo "\nFactorial using N\BigInteger\n";    
            // Benchmark Factorial using N\BigInteger                    
            for ($i = 5; $i <= 50; $i += 5)    
            {        
                    
                $timer->Start();        
                $facBigResult = FactorialBigInteger($i);        
                $timer->Stop();        
                echo " ({$i}) = {$timer->Elapsed->ToString()} : {$facBigResult->ToString()}\n";    
            }      
                          
            fgets(STDIN);      
            return 0;      
    }      
}    
?>

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:

 

Sunday, March 27, 2011

Factorial and Fibonacci in Nemerle



Here below a little program in Nemerle that implements 2 classes (in fact, they are 3). 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 there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "Main".

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 Nemerle
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using Nemerle.IO;

namespace FiborialN
{
    // Module = Static Class
    // all members become static by default
    // no need to explicitly use static on members (i did anyway)
    module StaticFiborial
    {
        // Static Field
        static mutable className : string; 
        // Static Constructor
        static this()
        {
            className = "Static Constructor";
            printf("%s", className);
        }
        // Static Method - Factorial Recursive
        public static FactorialR(n : int) : BigInteger
        {            
            if (n == 1)
                 BigInteger(1);
            else 
                 BigInteger(n) * FactorialR(n - 1);
        }
        // Static Method - Factorial Imperative
        public static FactorialI(n : int) : BigInteger
        {
            mutable res : BigInteger = BigInteger(1);
            for (mutable i : int = n; i >= 1; i--)
                res *= i;
            res;
        }
        // Static Method - Fibonacci Recursive
        public static FibonacciR(n : int) : long
        {
            def oneLong : long = 1;
            if (n < 2)
                oneLong;
            else
                FibonacciR(n - 1) + FibonacciR(n - 2);
        }
        // Static Method - Fibonacci Imperative
        public static FibonacciI(n : int) : long
        {            
            mutable pre : long = 1;
            mutable cur : long = 1;
            mutable tmp : long = 0;
            
            for (mutable i : int = 2; i <= n; i++)
            {
                tmp = cur + pre;
                pre = cur;
                cur = tmp;
            }
            cur;
        }
        // Static Method - Benchmarking Algorithms
        public static BenchmarkAlgorithm(algorithm : int, values : list[int]) : void
        {            
            def timer : Stopwatch = Stopwatch();
            mutable i : int = 0;
            mutable testValue : int = 0;
            mutable facTimeResult : BigInteger = BigInteger(0);
            mutable fibTimeResult : long = 0;
           
            // "Switch" Flow Constrol Statement
            match (algorithm)
            {
                | 1 =>
                    printf("\nFactorial Imperative:\n");
                    // "For" Loop Statement
                    for (i = 0; i < values.Length; i++)
                    {
                        testValue = values.Nth(i);
                        // Taking Time
                        timer.Start();
                        facTimeResult = FactorialI(testValue);
                        timer.Stop();                        
                        // Getting Time
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                    }
                | 2 =>
                    printf("\nFactorial Recursive:\n");
                    // 'While' Loop Statement  
                    while (i < values.Length) 
                    {
                        testValue = values.Nth(i);  
                        // Taking Time  
                        timer.Start();  
                        facTimeResult = FactorialR(testValue);  
                        timer.Stop();  
                        // Getting Time  
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                        i++;
                    }
                | 3 =>
                    printf("\nFibonacci Imperative:\n");
                    // 'Do-While' Loop Statement  
                    do {  
                        testValue = values.Nth(i);  
                        // Taking Time 
                        timer.Start();  
                        fibTimeResult = FibonacciI(testValue);  
                        timer.Stop();  
                        // Getting Time  
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                        i++;  
                    } while (i < values.Length);  
                | 4 =>
                    printf("\nFibonacci Recursive:\n");
                    // 'For Each' Loop Statement  
                    foreach (item : int in values) {  
                        testValue = item;
                        // Taking Time  
                        timer.Start();  
                        fibTimeResult = FibonacciR(testValue);  
                        timer.Stop();  
                        // Getting Time  
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                    }  
                | _ => printf("DONG!");
            }                
        }
    }
    
    // Instance Class  
    public class InstanceFiborial 
    {  
        // Instance Field  
        mutable className : String;  
        // Instance Constructor  
        public this() 
        {  
            this.className = "Instance Constructor";  
            printf("%s", this.className);
        }  
        // Instance Method - Factorial Recursive  
        public FactorialR(n : int) : BigInteger 
        {  
            // Calling Static Method  
            StaticFiborial.FactorialR(n);  
        }  
        // Instance Method - Factorial Imperative  
        public FactorialI(n : int) : BigInteger 
        {  
            // Calling Static Method  
            StaticFiborial.FactorialI(n);  
        }  
        // Instance Method - Fibonacci Recursive  
        public FibonacciR(n : int) : long 
        {  
            // Calling Static Method  
            StaticFiborial.FibonacciR(n);  
        }  
        // Instance Method - Factorial Imperative  
        public FibonacciI(n : int) : long 
        {  
            // Calling Static Method  
            StaticFiborial.FibonacciI(n);  
        }  
    }  
    
    module Program
    {
        Main() : void
        {          
            printf("\nStatic Class\n");
            // Calling Static Class and Methods  
            // No instantiation needed. Calling method directly from the class 
            printf("FacImp(5) = %s\n", StaticFiborial.FactorialI(5).ToString());  
            printf("FacRec(5) = %s\n", StaticFiborial.FactorialR(5).ToString());  
            printf("FibImp(11)= %s\n", StaticFiborial.FibonacciI(11).ToString());  
            printf("FibRec(11)= %s\n", StaticFiborial.FibonacciR(11).ToString());  

            printf("\nInstance Class\n");  
            // Calling Instance Class and Methods   
            // Need to instantiate before using. Calling method from instantiated object  
            def ff : InstanceFiborial = InstanceFiborial();  
            printf("FacImp(5) = %s\n", ff.FactorialI(5).ToString());  
            printf("FacRec(5) = %s\n", ff.FactorialR(5).ToString());  
            printf("FibImp(11)= %s\n", ff.FibonacciI(11).ToString());  
            printf("FibRec(11)= %s\n", ff.FibonacciR(11).ToString()); 

            // Create a (nemerle) list of integer values to test
            // From 5 to 50 by 5
            mutable values : list[int] = [];
            foreach (i in $[5,10..50])
                values ::= i;
                    
            // Benchmarking Fibonacci                       
            // 1 = Factorial Imperative              
            StaticFiborial.BenchmarkAlgorithm(1, values.Reverse());
            // 2 = Factorial Recursive  
            StaticFiborial.BenchmarkAlgorithm(2, values.Reverse());

            // Benchmarking Factorial              
            // 3 = Fibonacci Imperative  
            StaticFiborial.BenchmarkAlgorithm(3, values.Reverse());
            // 4 = Fibonacci Recursive  
            StaticFiborial.BenchmarkAlgorithm(4, values.Reverse());        

            // Stop and Exit 
            _ = Console.ReadLine();
        }
    }
}

And the Output is:






































Humm, looks like Fibonnaci's algorithm implemented using recursion is definitively more complex than the others 3 right? I will grab these results for this and each of the upcoming posts to prepare a comparison of time execution between all the programming languages, then we will be able to talk about the algorithm's complexity as well.

Printing the Factorial and Fibonacci Series
using System;  
using System.Text;  
using System.Numerics;
using Nemerle.IO;

namespace FiborialSeries
{
    static class Fiborial
    {
        // Using a StringBuilder as a list of string elements  
        public static GetFactorialSeries(n : int) : string
        {  
            // Create the String that will hold the list  
            def series : StringBuilder = StringBuilder();  
            // We begin by concatenating the number you want to calculate  
            // in the following format: "!# ="  
            _ = series.Append("!");
            _ = series.Append(n);  
            _ = series.Append(" = ");  
            // We iterate backwards through the elements of the series  
            for (mutable i : int = n; i <= n && i > 0; i--)  
            {  
                // and append it to the list  
                _ = series.Append(i);  
                if (i > 1)  
                    _ = series.Append(" * ");  
                else   
                    _ = series.Append(" = ");   
            }  
            // Get the result from the Factorial Method  
            // and append it to the end of the list  
            _ = series.Append(Factorial(n));  
            // return the list as a string  
            series.ToString();  
        }
        // Using a StringBuilder as a list of string elements  
        public static GetFibonnaciSeries(n : int) : string 
        {  
            // Create the String that will hold the list  
            def series : StringBuilder = StringBuilder();  
            // We begin by concatenating the first 3 values which  
            // are always constant  
            _ = series.Append("0, 1, 1");  
            // Then we calculate the Fibonacci of each element  
            // and add append it to the list  
            for (mutable i : int = 2; i <= n; i++)  
            {  
                if (i < n)  
                    _ = series.Append(", ");  
                else  
                    _ = series.Append(" = ");  
                  
                _ = series.Append(Fibonacci(i));  
            }  
            // return the list as a string  
            series.ToString();  
        }  
        // Static Method - Factorial Recursive
        public static Factorial(n : int) : BigInteger
        {            
            if (n == 1)
                 BigInteger(1);
            else 
                 BigInteger(n) * Factorial(n - 1);
        }        
        // Static Method - Fibonacci Recursive
        public static Fibonacci(n : int) : long
        {
            def oneLong : long = 1;
            if (n < 2)
                oneLong;
            else
                Fibonacci(n - 1) + Fibonacci(n - 2);
        }        
    }
        
    module Program
    {
        Main() : void
        {          
            printf("\nStatic Class\n");
            // Printing Factorial Series  
            printf("\n");
            printf("%s\n", Fiborial.GetFactorialSeries(5));
            printf("%s\n", Fiborial.GetFactorialSeries(7));  
            printf("%s\n", Fiborial.GetFactorialSeries(9));  
            printf("%s\n", Fiborial.GetFactorialSeries(11));  
            printf("%s\n", Fiborial.GetFactorialSeries(40));  
            // Printing Fibonacci Series  
            printf("\n");
            printf("%s\n", Fiborial.GetFibonnaciSeries(5));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(7));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(9));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(11));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(40));              
        }
    }
}

And the Output is:



















Mixing Instance and Static Members in the same Class

We can also define instance classes that have both, instance and static members such as: fields, properties, constructors, methods, etc. However, we cannot do that if the class is marked as static because of the features mentioned in the previous post:
The main features of a static class are:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors

using System;  
namespace FiborialExtrasN2
{
    // Instance Class
    class Fiborial  
    {  
        // Instance Field  
        mutable instanceCount : int;  
        // Static Field  
        static mutable staticCount : int;          
        // Instance Read-Only Property  
        // Within instance members, you can always use    
        // the "this" reference pointer to access your (instance) members.  
        public InstanceCount : int
        {  
            get { this.instanceCount; }  
        }  
        // Static Read-Only Property  
        // Remeber that Properties are Methods to the CLR, so, you can also  
        // define static properties for static fields.   
        // As with Static Methods, you cannot reference your class members  
        // with the "this" reference pointer since static members are not  
        // instantiated.          
        public static StaticCount : int
        {  
            get { staticCount; }  
        }  
        // Instance Constructor  
        public this()  
        {  
            this.instanceCount = 0;  
            Console.WriteLine("\nInstance Constructor {0}", this.instanceCount);  
        }  
        // Static Constructor  
        static this()  
        {  
            staticCount = 0;  
            Console.WriteLine("\nStatic Constructor {0}", staticCount);  
        }  
  
        // Instance Method  
        public Factorial(n : int) : void
        {  
            this.instanceCount += 1;  
            Console.WriteLine("\nFactorial({0})", n);  
        }  
  
        // Static Method  
        public static Fibonacci(n : int) : void
        {  
            staticCount += 1;  
            Console.WriteLine("\nFibonacci({0})", n);  
        }                   
    }
        
    module Program
    {
        Main() : void
        {          
            // Calling Static Constructor and Methods  
            // No need to instantiate  
            Fiborial.Fibonacci(5);              
  
            // Calling Instance Constructor and Methods  
            // Instance required  
            def fib : Fiborial = Fiborial();  
            fib.Factorial(5);              
  
            Fiborial.Fibonacci(15);              
            fib.Factorial(5);  
  
            // Calling Instance Constructor and Methods  
            // for a second object  
            def fib2 : Fiborial = Fiborial();  
            fib2.Factorial(5);  
              
            Console.WriteLine();  
            // Calling Static Property  
            Console.WriteLine("Static Count = {0}", Fiborial.StaticCount);  
            // Calling Instance Property of object 1 and 2  
            Console.WriteLine("Instance 1 Count = {0}", fib.InstanceCount);  
            Console.WriteLine("Instance 2 Count = {0}", fib2.InstanceCount); 
        }
    }
}

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 "tried" to say, lets have a look at the following code and the output we get.

#pragma indent
using System;  
using System.Numerics;  
using System.Diagnostics;  
using System.Console;

namespace FiborialExtrasCs3

    module Program
        // Long Factorial
        public static FactorialInt64(n : int) : long
            def oneLong : long = 1;
            if (n == 1)
                 oneLong;
            else 
                 n * FactorialInt64(n - 1);

        // Double Factorial
        public static FactorialDouble(n : int) : double
            def oneDouble : double = 1;
            if (n == 1)
                oneDouble;
            else 
                 n * FactorialDouble(n - 1);

        // BigInteger Factorial
        public static FactorialBigInteger(n : int) : BigInteger
            if (n == 1)
                 BigInteger(1);
            else 
                 BigInteger(n) * FactorialBigInteger(n - 1);
    
        Main() : void
            def timer : Stopwatch = Stopwatch();  
            mutable facIntResult : long = 0;  
            mutable facDblResult : double = 0;  
            mutable facBigResult : BigInteger = BigInteger(0);
                        
            WriteLine("\nFactorial using Int64");
            // Benchmark Factorial using Int64
            // Overflow Exception!!!
            try
                foreach (i in $[5,10..50])
                    timer.Start();  
                    facIntResult = FactorialInt64(i);  
                    timer.Stop();
                    WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facIntResult);  
            catch
                | ex is OverflowException =>
                    // yummy ^_^  
                    WriteLine("Oops! {0}", ex.Message);
            
            WriteLine("\nFactorial using Double");  
            // Benchmark Factorial using Double  
            foreach (i in $[5,10..50])
                timer.Start();  
                facDblResult = FactorialDouble(i);
                timer.Stop();
                WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facDblResult);  
            
            WriteLine("\nFactorial using BigInteger");  
            // Benchmark Factorial using BigInteger
            foreach (i in $[5,10..50])
                timer.Start();
                facBigResult = FactorialBigInteger(i);
                timer.Stop();
                WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facBigResult);

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: