Friday, October 21, 2011

Factorial and Fibonacci in JRuby



Here below a little program in JRuby 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 there just to show the difference between static and instance classes, and finally a main function called as module level code.

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 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 

WARNING: the code that you will see below is not following ruby guidelines/idiomatic coding, I did it in purpose to compare ruby's syntax and features side by side with other programming languages... For instance, instead of using a ruby bignum I imported and used java.math.BigInteger instead. Other examples, naming convention and so on, so bear with me!

I'm using the same Stopwatch java class that I used in the Java version of this post. I just added the .class into a 'target' folder and added it to the classpath. then I java_imported it. http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html 

The Fiborial Program

# Factorial and Fibonacci in JRuby  
require "java"    
$CLASSPATH << "target"
java_import 'Stopwatch'
import java.lang.System
import java.math.BigInteger
    
module FiborialRb  
    # Static Class  
    # static classes are not supported in Ruby  
    class StaticFiborial  
        # Static Field  
        @@class_name = ""  
        # no builtin static constructor/initializer support    
        # you can initialize field at this point and even add extra code           
        @@class_name = "Static Constructor"  
        puts @@class_name  
        # Static Method - Factorial Recursive  
        def self.factorial_r(n)  
            if n < 2  
                BigInteger.new('1')
            else                
                BigInteger.new(n.to_s).multiply(self.factorial_r(n-1))
            end  
        end  
        # Static Method - Factorial Imperative  
        def self.factorial_i(n)  
            res = BigInteger.new('1')
            while n > 1                    
                res = BigInteger.new(res.multiply(n).to_s)
                n -= 1  
            end  
            res  
        end  
        # Static Method - Fibonacci Recursive     
        def self.fibonacci_r(n)  
            if n < 2  
                1  
            else  
                self.fibonacci_r(n - 1) + self.fibonacci_r(n - 2)  
            end  
        end  
        # Static Method - Fibonacci Imperative  
        def self.fibonacci_i(n)  
            pre = 1  
            cur = 1  
            tmp = 0  
            for i in 2..n
                tmp = cur + pre  
                pre = cur  
                cur = tmp  
            end  
            cur  
        end  
        # Static Method - Benchmarking Algorithms  
        def self.benchmark_algorithm(algorithm, values)  
            timer = Stopwatch.new    
            i = 0  
            testValue = 0      
            facTimeResult = BigInteger::ZERO    
            fibTimeResult = 0             
            # "case/switch" Flow Control Statement  
            case algorithm  
            when 1  
                puts "\nFactorial Imperative:"  
                # "For in range" Loop Statement  
                for i in 0..values.size - 1 do  
                    testValue = values[i]                      
                    # Taking Time  
                    timer.start  
                    facTimeResult = self.factorial_i(testValue)      
                    timer.stop  
                    # Getting Time  
                    puts " (#{testValue}) = #{timer.elapsed}"                      
                end  
            when 2  
                puts "\nFactorial Recursive:"  
                # "While" Loop Statement  
                while i < values.size do  
                    testValue = values[i]  
                    # Taking Time  
                    timer.start  
                    facTimeResult = self.factorial_r(testValue)      
                    timer.stop  
                    # Getting Time  
                    puts " (#{testValue}) = #{timer.elapsed}"  
                    i += 1  
                end  
            when 3  
                puts "\nFibonacci Imperative:"  
                # "until" Loop Statement  
                until i == values.size do                      
                    testValue = values[i]  
                    # Taking Time  
                    timer.start  
                    fibTimeResult = self.fibonacci_i(testValue)      
                    timer.stop  
                    # Getting Time  
                    puts " (#{testValue}) = #{timer.elapsed}"  
                    i += 1  
                end  
            when 4  
                puts "\nFibonacci Recursive:"  
                # "For each?" Statement  
                values.each do |testValue|  
                    # Taking Time  
                    timer.start  
                    fibTimeResult = self.fibonacci_r(testValue)      
                    timer.stop  
                    # Getting Time  
                    puts " (#{testValue}) = #{timer.elapsed}"  
                end  
            else  
                puts "DONG!"  
            end  
        end  
    end  
      
    # Instance Class  
    class InstanceFiborial  
        # Instance Field  
        @class_name = ""  
        # Instance Constructor/Initializer  
        def initialize  
            @class_name = "Instance Constructor"  
            puts @class_name  
        end  
        # Instance Method - Factorial Recursive      
        def factorial_r(n)    
            # Calling Static Method      
            StaticFiborial::factorial_r(n)  
        end  
        # Instance Method - Factorial Imperative      
        def factorial_i(n)  
            # Calling Static Method      
            StaticFiborial::factorial_i(n)      
        end  
        # Instance Method - Fibonacci Recursive        
        def fibonacci_r(n)  
            # Calling Static Method      
            StaticFiborial::fibonacci_r(n)      
        end  
        # Instance Method - Fibonacci Imperative      
        def fibonacci_i(n)  
            # Calling Static Method      
            StaticFiborial::fibonacci_i(n)  
        end  
    end  
    
    # Console Program    
    puts "Static Class"      
    # Calling Static Class and Methods      
    # No instantiation needed. Calling method directly from the class      
    puts "FacImp(5) = #{StaticFiborial::factorial_i(5)}"  
    puts "FacRec(5) = #{StaticFiborial::factorial_r(5)}"   
    puts "FibImp(11)= #{StaticFiborial::fibonacci_i(11)}"   
    puts "FibRec(11)= #{StaticFiborial::fibonacci_r(11)}"   
      
    puts "\nInstance Class"  
    # Calling Instance Class and Methods      
    # Need to instantiate before using. Calling method from instantiated object      
    ff = InstanceFiborial.new  
    puts "FacImp(5) = #{ff.factorial_i(5)}"  
    puts "FacRec(5) = #{ff.factorial_r(5)}"  
    puts "FibImp(11)= #{ff.fibonacci_i(11)}"  
    puts "FibRec(11)= #{ff.fibonacci_r(11)}"  
          
    # Create a (Ruby) list of values to test        
    # From 5 to 50 by 5      
    values = []  
    for i in (5..50).step(5)  
        values << i  
    end  
  
    # Benchmarking Fibonacci      
    # 1 = Factorial Imperative     
    StaticFiborial::benchmark_algorithm(1,values)  
     # 2 = Factorial Recursive  
    StaticFiborial::benchmark_algorithm(2,values)  
    # Benchmarking Factorial      
    # 3 = Fibonacci Imperative   
    StaticFiborial::benchmark_algorithm(3,values)  
    # 4 = Fibonacci Recursive   
    StaticFiborial::benchmark_algorithm(4,values)  
      
    # Stop and exit    
    puts "Press any key to exit..."    
    gets    
end

And the Output is:



































Printing the Factorial and Fibonacci Series

require 'java'
import java.lang.StringBuffer
import java.math.BigInteger

module FiborialSeriesRb

    class Fiborial  
         # Using a StringBuffer as a list of string elements    
         def self.get_factorial_series(n)  
            # Create the String to hold the list        
            series = StringBuffer.new      
            # 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  
            i = n  
            while i >= 1  
                # and append it to the list        
                series.append(i)      
                if i > 1       
                    series.append(" * ")        
                else  
                    series.append(" = ")      
                end  
                i -= 1  
            end  
            # Get the result from the Factorial Method        
            # and append it to the end of the list        
            series.append(self.factorial(n).to_s)  
            # return the list as a string  
            series.to_s  
         end  
           
         # Using a StringBuffer as a list of string elements  
         def self.get_fibonnaci_series(n)  
            # Create the String that will hold the list        
            series = StringBuffer.new  
            # 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 in 2..n      
                if i < n      
                    series.append(", ")       
                else   
                    series.append(" = ")  
                end  
                series.append(self.fibonacci(i))  
            end  
            # return the list as a string        
            series.to_s    
         end  
           
        def self.factorial(n)  
            if n < 2  
                BigInteger.new('1')
            else  
                BigInteger.new(n.to_s).multiply(self.factorial(n-1))
            end  
        end  
          
        def self.fibonacci(n)
            if n < 2  
                1  
            else  
                self.fibonacci(n - 1) + self.fibonacci(n - 2)  
            end  
        end  
    end  
      
    # Printing Factorial Series        
    puts ""      
    puts Fiborial::get_factorial_series(5)      
    puts Fiborial::get_factorial_series(7)      
    puts Fiborial::get_factorial_series(9)      
    puts Fiborial::get_factorial_series(11)      
    puts Fiborial::get_factorial_series(40)      
    # Printing Fibonacci Series        
    puts ""      
    puts Fiborial::get_fibonnaci_series(5)      
    puts Fiborial::get_fibonnaci_series(7)      
    puts Fiborial::get_fibonnaci_series(9)      
    puts Fiborial::get_fibonnaci_series(11)      
    puts Fiborial::get_fibonnaci_series(40)   
      
    # Stop and exit    
    puts "Press any key to exit..."    
    gets    
end

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.
require 'java'
 
# Instance Class    
class Fiborial  
    # Instance Field      
    @instance_count = 0  
    # Static Field  
    @@static_count = 0      
    # Instance Read-Only Getter  
    def get_instance_count()       
        @instance_count      
    end      
    # Static Read-Only Getter  
    def self.get_static_count()
        @@static_count  
    end      
    # Instance Constructor/Initializer  
    def initialize()    
        @instance_count = 0  
        puts "\nInstance Constructor #{@instance_count}"  
    end  
    # No Static Constructor/Initializer  
    # You can do a self.initialize() static method, but it will not be called  
    #def self.initialize()  
    #    @@static_count = 0    
    #    puts "\nStatic Constructor #{@@static_count}"  
    # Instance Method  
    def factorial(n)    
        @instance_count += 1       
        puts "\nFactorial(#{n.to_s})"  
    end  
    # Static Method     
    def self.fibonacci(n)  
        @@static_count += 1      
        puts "\nFibonacci(#{n.to_s})"  
    end          
    
    # Calling Static Constructor 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)      
          
    puts ""  
    # Calling Static Getter      
    puts "Static Count = #{Fiborial::get_static_count}"   
    # Calling Instance Property of object 1 and 2        
    puts "Instance 1 Count = #{fib.get_instance_count}"  
    puts "Instance 2 Count = #{fib2.get_instance_count}"  
          
    gets  
end

And the Output is:



















Factorial using int, float, System.Numerics.BigInteger


So, it looks like integers in ruby can hold big integers (they are handled as bignum), so using JRuby int/long or java.math.BigInteger is the same so not much to say here.

require 'java'
$CLASSPATH << "target"
java_import 'Stopwatch'
import java.math.BigInteger
      
# Int/Long Factorial      
def factorial_int(n)  
    if n == 1  
        1.to_i  
    else      
        (n * factorial_int(n - 1)).to_i  
    end  
end  
# double/float Factorial  
def factorial_float(n)  
    if n == 1    
        1.0
    else  
        (n * factorial_float(n - 1)).to_f  
    end  
end  
# BigInteger Factorial         
def factorial_bigint(n)  
    if n == 1    
        BigInteger.new('1')  
    else            
        BigInteger.new(n.to_s).multiply(factorial_bigint(n-1))
    end  
end  
  
timer = Stopwatch.new  
facIntResult = 0    
facDblResult = 0.0      
facBigResult = BigInteger.new('0')  
i = 0      
          
puts "\nFactorial using Int/Long"  
# Benchmark Factorial using Int64        
for i in (5..50).step(5)  
    timer.start   
    facIntResult = factorial_int(i)  
    timer.stop  
    puts " (#{i.to_s}) = #{timer.elapsed} : #{facIntResult}"  
end  
puts "\nFactorial using Float/Double"  
# Benchmark Factorial using Double  
for i in (5..50).step(5)  
    timer.start      
    facDblResult = factorial_float(i)      
    timer.stop  
    puts " (#{i.to_s}) = #{timer.elapsed.to_s} : #{facDblResult.to_s}"  
end          
puts "\nFactorial using BigInteger"      
# Benchmark Factorial using BigInteger      
for i in (5..50).step(5)  
    timer.start  
    facBigResult = factorial_bigint(i)  
    timer.stop  
    puts " (#{i.to_s}) = #{timer.elapsed.to_s} : #{facBigResult.to_s}"  
end  
  
gets

And the Output is:


Saturday, October 15, 2011

Factorial and Fibonacci in Scala



Update 1: Porting code examples to Scala 2.10.1 - support for String Interpolation.

WARNING! I know that Scala is intended to be use in a very Functional way, however, my goal is to show its Imperative and OO language features, so it can be compared with other 19 OO languages. Said that, if you know how to do something on the examples below in a more Functional style you can add it in a comment :)

Here below a little program in Scala 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 

I'm using the same Stopwatch java class that I used in the Java version of this post. I just added the .java file in the same scala-eclipse project. http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html

The Fiborial Program

package com.series
import scala.math.BigInt._  
import java.util.Scanner
import blog.series.lib.Stopwatch

// Instance (Singleton) Class that works as a Module/Utils class             
// static is not a class modifier in Scala    
object StaticFiborial  
{  
    // 'Static' Field  
    // 'Static' Constructor/Initializer  
    private var _message:String = "'Static' Constructor"  
    println(_message)  
    // 'Static' Method - Factorial Recursive    
    def factorialR(n:Int):BigInt = {  
        if(n==1)  
            BigInt(1)  
        else  
            BigInt(n) * factorialR(n - 1)  
    }  
    // 'Static' Method - Factorial Imperative  
    def factorialI(n:Int):BigInt = {  
        var res:BigInt = 1        
        for (i <- n until 1 by -1) {  
            res = res * i  
        }        
        res  
    }  
    // 'Static' Method - Fibonacci Recursive   
    def fibonacciR(n:Int):Long = {  
        if(n<2)  
            1  
        else  
            fibonacciR(n - 1) + fibonacciR(n - 2)  
    }  
    // 'Static' Method - Fibonacci Imperative  
    def fibonacciI(n:Int):Long = {  
        var pre:Long = 1  
        var cur:Long = 1  
        var tmp:Long = 0  
        for(i <- 2 to n) {  
            tmp = cur + pre  
            pre = cur  
            cur = tmp  
        }  
        cur  
    }  
    // Static Method - Benchmarking Algorithms   
    def benchmarkAlgorithm(algorithm:Int, values:List[Int]) = {        
        val timer = new Stopwatch  
        var (i:Int, testValue:Int) = (0, 0)  
        var facTimeResult:BigInt = 0  
        var fibTimeResult:Long = 0  
        
        algorithm match {    
            case 1 =>   
                println("\nFactorial Imperative:")  
                // "For" Loop Statement  
                for (i <- 0 to values.size - 1) {  
                    testValue = values(i)  
                    // Taking Time      
                    timer.start()      
                    facTimeResult = factorialI(testValue)      
                    timer.stop()  
                    // Getting Time  
                    println(s" ($testValue) = ${timer.getElapsed}")  
                }  
            case 2 =>   
                println("\nFactorial Recursive:")  
                // "While" Loop Statement  
                while (i < values.size) {  
                    testValue = values(i)  
                    // Taking Time      
                    timer.start()      
                    facTimeResult = factorialR(testValue)      
                    timer.stop()  
                    // Getting Time  
                    println(s" ($testValue) = ${timer.getElapsed}")  
                    i += 1  
                }  
            case 3 =>  
                println("\nFibonacci Imperative:")  
                // "For" Loop Statement  
                for (i <- 0 to values.size - 1) {  
                    testValue = values(i)  
                    // Taking Time      
                    timer.start()      
                    fibTimeResult = fibonacciI(testValue)  
                    timer.stop()  
                    // Getting Time  
                    println(s" ($testValue) = ${timer.getElapsed}")  
                }  
            case 4 =>   
                println("\nFibonacci Recursive:")  
                // "For" Loop Statement  
                for (i <- 0 to values.size - 1) {  
                    testValue = values(i)  
                    // Taking Time      
                    timer.start()      
                    fibTimeResult = fibonacciR(testValue)  
                    timer.stop()  
                    // Getting Time  
                    println(s" ($testValue) = ${timer.getElapsed}")  
                }  
            case _ =>   
                println("DONG!")  
        }    
    }      
}  
  
class InstanceFiborial(message:String) {  
    // Instance Field  
    private var _message:String = message  
    // Instance Constructor      
    def this() = {  
        this("Instance Constructor")  
        println(_message)  
    }      
    // Instance Method - Factorial Recursive    
    def factorialR(n:Int):BigInt = {  
        // Calling 'Static' Method  
        StaticFiborial.factorialR(n)  
    }  
    // Instance Method - Factorial Imperative  
    def factorialI(n:Int):BigInt = {  
        // Calling 'Static' Method        
        StaticFiborial.factorialI(n)  
    }  
    // Instance Method - Fibonacci Recursive   
    def fibonacciR(n:Int):Long = {  
        // Calling 'Static' Method        
        StaticFiborial.fibonacciR(n)  
    }  
    // Instance Method - Fibonacci Imperative  
    def fibonacciI(n:Int):Long = {  
        // Calling 'Static' Method        
        StaticFiborial.fibonacciI(n)  
    }  
}  
  
object Program {  
    def main(args: Array[String]): Unit = {  
        // Calling 'Static' Class and Methods      
        // No instantiation needed. Calling method directly from the class      
        println(s"FacImp(5) = ${StaticFiborial.factorialI(5)}")      
        println(s"FacRec(5) = ${StaticFiborial.factorialR(5)}")      
        println(s"FibImp(11)= ${StaticFiborial.fibonacciI(11)}")      
        println(s"FibRec(11)= ${StaticFiborial.fibonacciR(11)}")   
          
        println("\nInstance Class")      
        // Calling Instance Class and Methods       
        // Need to instantiate before using. Call method from instantiated object      
        val ff = new InstanceFiborial()      
        println(s"FacImp(5) = ${ff.factorialI(5)}")      
        println(s"FacRec(5) = ${ff.factorialR(5)}")      
        println(s"FibImp(11)= ${ff.fibonacciI(11)}")      
        println(s"FibRec(11)= ${ff.fibonacciR(11)}")  
          
        // Create a (generic) list of integer values to test      
        // From 5 to 50 by 5  
        var values:List[Int] = Nil  
        for(i <- 5 until 55 by 5)  
            values = values ::: List(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)  
  
        println("Press any key to exit...")      
        val in = new Scanner(System.in)      
        in.nextLine()      
        in.close()           
    }  
}

And the Output is:





































Printing the Factorial and Fibonacci Series


import scala.math.BigInt._
import scala.collection.mutable.StringBuilder._

object Fiborial {
    // Using a StringBuilder as a list of string elements
    def getFactorialSeries(n:Int):String = {
        // Create the String that will hold the list
        val series:StringBuilder = new 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 until 0 by -1) {
            // 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
    def getFibonnaciSeries(n:Int):String = {
        // Create the String that will hold the list
        val series:StringBuilder = new 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 to n) {
            if (i < n)
                series.append(", ")
            else
                series.append(" = ")
            
            series.append(fibonacci(i))
        }
        // return the list as a string
        series.toString
    }

    def factorial(n:Int):BigInt = {
        if(n==1)
            BigInt(1)
        else
            BigInt(n) * factorial(n - 1)
    }

    def fibonacci(n:Int):Long = {
        if (n < 2)
            1  
        else  
            fibonacci(n - 1) + fibonacci(n - 2)  
    }
}

object FiborialProgram {
    def main(args:Array[String]) {
        // Printing Factorial Series  
        println("")
        println(Fiborial.getFactorialSeries(5))
        println(Fiborial.getFactorialSeries(7))  
        println(Fiborial.getFactorialSeries(9))  
        println(Fiborial.getFactorialSeries(11))  
        println(Fiborial.getFactorialSeries(40))  
        // Printing Fibonacci Series  
        println("")  
        println(Fiborial.getFibonnaciSeries(5))  
        println(Fiborial.getFibonnaciSeries(7))  
        println(Fiborial.getFibonnaciSeries(9))  
        println(Fiborial.getFibonnaciSeries(11))  
        println(Fiborial.getFibonnaciSeries(40))  
    }
}

And the Output is:

















Mixing Instance and Static Members in the same Class

There are no static classes in Scala, instead you can define an object which in fact is an instance singleton class that can be used as a static class. It is possible to mix 'static' and instance members into the same class. You do that by creating a class (instance members) and an object ('static' members)

package com.series
// To mix Instance and 'Static' methods in Scala you define a Class (instance)   
// and and object (static) with the same Name  
  
// Instance Class  
class Fiborial(init:Int) {  
    // Instance Field  
    private var _instanceCount:Int = init  
    // Instance Read-Only Getter  
    def InstanceCount = _instanceCount  
    // Instance Constructor  
    def this() = {  
        this(0)  
        println(s"\nInstance Constructor ${_instanceCount}")  
    }      
    // Instance Method   
    def factorial(n:Int) = {  
        _instanceCount += 1      
        println(s"\nFactorial($n)")  
    }  
}  
// 'Static' Class  
object Fiborial {  
    // 'Static' Field  
    private var _staticCount:Int = 0  
    // Instance Read-Only Getter  
    def StaticCount = _staticCount  
    // 'Static' Constructor/Initializer  
    println(s"\nStatic Constructor ${_staticCount}")  
    // 'Static' Method   
    def fibonacci(n:Int) = {  
        _staticCount += 1      
        println(s"\nFactorial($n)")  
    }  
}  
  
object Program {  
    def main(args: Array[String]) = {  
        // Calling Static Constructor and Methods  
        // No need to instantiate      
        Fiborial.fibonacci(5)                  
    
        // Calling Instance Constructor and Methods      
        // Instance required      
        val fib = new Fiborial      
        fib.factorial(5)    
    
        Fiborial.fibonacci(15)                  
        fib.factorial(5)      
    
        // Calling Instance Constructor and Methods      
        // for a second object      
        val fib2 = new Fiborial      
        fib2.factorial(5)      
              
        println("")  
        // Calling Static Property      
        println(s"Static Count = ${Fiborial.StaticCount}")      
        // Calling Instance Getter of object 1 and 2      
        println(s"Instance 1 Count = ${fib.InstanceCount}")      
        println(s"Instance 2 Count = ${fib2.InstanceCount}")     
    }  
}

And the Output is:























Factorial using scala.Long, scala.Double, scala.math.BigInt

import scala.math.BigInt._
import blog.series.lib.Stopwatch

object Program {

    def main(args: Array[String]): Unit = {
        val timer = new Stopwatch()  
        var facLngResult:Long = 0  
        var facDblResult:Double = 0  
        var facBigResult:BigInt = BigInt(0)  
            
        println("\nFactorial using Long")    
        // Benchmark Factorial using Long  
        for(i <- 5 until 55 by 5) {            
            timer.start   
            facLngResult = factorialLong(i)    
            timer.stop  
            println(s" ($i) = ${timer.getElapsed} : $facLngResult")    
        }  
        println("\nFactorial using Double")  
        // Benchmark Factorial using Double    
        for(i <- 5 until 55 by 5) {            
            timer.start    
            facDblResult = factorialDouble(i)    
            timer.stop    
            println(s" ($i) = ${timer.getElapsed} : $facDblResult")  
        }  
        println("\nFactorial using BigInteger")  
        // Benchmark Factorial using BigInteger  
        for(i <- 5 until 55 by 5) {            
            timer.start    
            facBigResult = factorialBigInt(i)    
            timer.stop    
            println(s" ($i) = ${timer.getElapsed} : $facBigResult")  
        }  
    }  
    // Long Factorial   
    def factorialLong(n:Int):Long = {      
        if(n==1)  
            1.toLong  
        else  
            n.toLong * factorialLong(n - 1)  
    }  
    // Double Factorial   
    def factorialDouble(n:Int):Double = {  
        if(n==1)  
            1.toDouble  
        else  
            n.toDouble * factorialDouble(n - 1)  
    }  
    // BigInteger Factorial     
    def factorialBigInt(n:Int):BigInt = {       
        if(n==1)  
            BigInt(1)  
        else  
            BigInt(n) * factorialBigInt(n - 1)  
    }  

}

And the Output is:



Sunday, October 2, 2011

Factorial and Fibonacci in Jython



Here below a little program in Jython 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 there just to show the difference between static and instance classes, and finally a main function called as module level code.

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 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 

WARNING: the code that you will see below is not following python(ic) guidelines/idiomatic coding, I did it in purpose to compare python's syntax and features side by side with other programming languages... For instance, instead of using a python int or long I imported and used System.Numerics.BigInteger instead. Other examples, naming convention and so on, so bear with me!

I'm using the same Stopwatch java class that I used in the Java version of this post. I just added the .class in the python paths. http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html

The Fiborial Program

# Factorial and Fibonacci in Jython
import java
from java.util import Scanner
from java.math import BigInteger
from java.lang import System 
import Stopwatch

# Instance Class
# static classes are not supported in Python
class StaticFiborial:
    # Static Field
    __className = ''
    # no builtin static constructor/initializer support
    # you can initialize field at this point and even add extra code
    __className = 'Static Initializer'
    print __className
    # Static Method - Factorial Recursive  
    @staticmethod
    def factorialR(n):
        if n == 1:
            return BigInteger.ONE
        else:            
            return BigInteger.valueOf(n).multiply(StaticFiborial.factorialR(n-1))            
    # Static Method - Factorial Imperative
    @staticmethod
    def factorialI(n):
        res = BigInteger.ONE
        for i in range(n, 1, -1):            
            res = res.multiply(BigInteger.valueOf(i))
        return res
    # Static Method - Fibonacci Recursive 
    @staticmethod
    def fibonacciR(n):
        if n < 2:
            return 1
        else:
            return StaticFiborial.fibonacciR(n - 1) + StaticFiborial.fibonacciR(n - 2)
    # Static Method - Fibonacci Imperative
    @staticmethod
    def fibonacciI(n):
        pre, cur, tmp = 0, 0, 0
        pre, cur = 1, 1
        for i in range(2, n + 1):  
            tmp = cur + pre  
            pre = cur  
            cur = tmp  
        return cur 
    # Static Method - Benchmarking Algorithms 
    @staticmethod
    def benchmarkAlgorithm(algorithm, values):
        timer = Stopwatch()
        i = 0  
        testValue = 0  
        facTimeResult = BigInteger.valueOf(0)
        fibTimeResult = 0    
          
        # 'if-elif-else' Flow Control Statement    
        if algorithm == 1:  
            print '\nFactorial Imperative:'  
            # 'For in range' Loop Statement   
            for i in range(len(values)):
                testValue = values[i]  
                # Taking Time    
                timer.start()  
                facTimeResult = StaticFiborial.factorialI(testValue)  
                timer.stop()                            
                # Getting Time    
                print ' (' + str(testValue) + ') = ', timer.elapsed  
        elif algorithm == 2:  
            print '\nFactorial Recursive:'  
            # 'While' Loop Statement  
            while i < len(values):  
                testValue = values[i]  
                # Taking Time    
                timer.start()  
                facTimeResult = StaticFiborial.factorialR(testValue)  
                timer.stop()                            
                # Getting Time    
                print ' (' + str(testValue) + ') = ', timer.elapsed
                i += 1  
        elif algorithm == 3:  
            print '\nFibonacci Imperative:'   
            # 'For in List' Loop Statement               
            for item in values:
                testValue = item  
                # Taking Time  
                timer.start()  
                fibTimeResult = StaticFiborial.fibonacciI(testValue)  
                timer.stop()  
                # Getting Time  
                print ' (' + str(testValue) + ') = ', timer.elapsed                  
        elif algorithm == 4:
            print '\nFibonacci Recursive:'  
            # 'For in List' Loop Statement   
            for item in values:  
                testValue = item  
                # Taking Time  
                timer.start()  
                fibTimeResult = StaticFiborial.fibonacciR(testValue)  
                timer.stop()  
                # Getting Time                
                print ' (' + str(testValue) + ') = ', timer.elapsed
        else:  
            print 'DONG!'

# Instance Class  
class InstanceFiborial(object):
    # Instances Field  
    __className = ''
    # Instance Constructor  
    def __init__(self):  
        self.__className = 'Instance Constructor'
        print self.__className  
    # Instance Method - Factorial Recursive  
    def factorialR(self, n):
        # Calling Static Method  
        return StaticFiborial.factorialR(n)  
    # Instance Method - Factorial Imperative  
    def factorialI(self, n):  
        # Calling Static Method  
        return StaticFiborial.factorialI(n)  
    # Instance Method - Fibonacci Recursive    
    def fibonacciR(self, n):
        # Calling Static Method  
        return StaticFiborial.fibonacciR(n)  
    # Instance Method - Fibonacci Imperative  
    def fibonacciI(self, n):  
        # Calling Static Method  
        return StaticFiborial.fibonacciI(n)  


# Console Program  
def main():
    print 'Static Class'  
    # Calling Static Class and Methods  
    # No instantiation needed. Calling method directly from the class  
    print 'FacImp(5) = ', StaticFiborial.factorialI(5)
    print 'FacRec(5) = ', StaticFiborial.factorialR(5)
    print 'FibImp(11)= ', StaticFiborial.fibonacciI(11)
    print 'FibRec(11)= ', StaticFiborial.fibonacciR(11)
  
    print '\nInstance Class'  
    # Calling Instance Class and Methods  
    # Need to instantiate before using. Calling method from instantiated object  
    ff = InstanceFiborial()
    print 'FacImp(5) = ', ff.factorialI(5)
    print 'FacRec(5) = ', ff.factorialR(5)
    print 'FibImp(11)= ', ff.fibonacciI(11)
    print 'FibRec(11)= ', ff.fibonacciR(11)
  
    # Create a (Python) list of values to test    
    # From 5 to 50 by 5  
    values = []
    for i in range(5,55,5):
        values.append(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
    sin = Scanner(System.in)    
    line = sin.nextLine()    
    sin.close()
  
if __name__ == '__main__':
    main()

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
import java
from java.util import Scanner
from java.math import BigInteger
from java.lang import System, StringBuffer

class Fiborial:  
    # Using a StringBuffer as a list of string elements    
    @staticmethod
    def getFactorialSeries(n):
        # Create the String that will hold the list    
        series = 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 i in range(n, 0, -1):
            # 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(Fiborial.factorial(n).toString())
        # return the list as a string    
        return series.toString()  
  
    # Using a StringBuffer as a list of string elements    
    @staticmethod
    def getFibonnaciSeries(n):  
        # Create the String that will hold the list    
        series = 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 i in range(2, n+1):  
            if i < n:  
                series.append(", ")   
            else:  
                series.append(" = ")    
            series.append(Fiborial.fibonacci(i))  
        # return the list as a string    
        return series.toString()  
    @staticmethod      
    def factorial(n):
        if n == 1:
            return BigInteger.ONE
        else:
            return BigInteger.valueOf(n).multiply(Fiborial.factorial(n-1))
    @staticmethod  
    def fibonacci(n):  
        if n < 2:  
            return 1    
        else:    
            return Fiborial.fibonacci(n - 1) + Fiborial.fibonacci(n - 2)  
  
def main():
    # Printing Factorial Series    
    print ""  
    print Fiborial.getFactorialSeries(5)  
    print Fiborial.getFactorialSeries(7)  
    print Fiborial.getFactorialSeries(9)  
    print Fiborial.getFactorialSeries(11)  
    print Fiborial.getFactorialSeries(40)  
    # Printing Fibonacci Series    
    print ""  
    print Fiborial.getFibonnaciSeries(5)  
    print Fiborial.getFibonnaciSeries(7)  
    print Fiborial.getFibonnaciSeries(9)  
    print Fiborial.getFibonnaciSeries(11)  
    print Fiborial.getFibonnaciSeries(40)  
      
    sin = Scanner(System.in)    
    line = sin.nextLine()    
    sin.close()
  
if __name__ == '__main__':
    main()

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.

import java
from java.util import Scanner
from java.lang import System
    
# Instance Class
class Fiborial:
    # Instance Field  
    __instanceCount = 0
    # Static Field      
    __staticCount = 0    
    print "\nStatic Constructor", __staticCount
    # Instance Read-Only Property    
    # Within instance members, you can always use      
    # the "self" reference pointer to access your (instance) members.              
    def getInstanceCount(self):   
        return self.__instanceCount  
    InstanceCount = property(getInstanceCount, None, None)
    # Static Property
    # looks like it is not supported even if the code identify it as such    
    @staticmethod
    def getStaticCount():        
        return Fiborial.__staticCount        
    #StaticCount = property(getStaticCount, None, None)
    # The problem seems to be the use of: property(getStaticCount,..)
    # it requires an instance method and not a static one (Test.getStaticCount)    
    # Instance Constructor    
    def __init__(self):
        self.__instanceCount = 0    
        print "\nInstance Constructor", self.__instanceCount
    # No Static Constructor    
    #@staticmethod
    #def __init__():
    #    Fiborial.__staticCount = 0
    #    print "\nStatic Constructor", Fiborial.__staticCount
    # Instance Method
    def factorial(self, n):
        self.__instanceCount += 1   
        print "\nFactorial(" + str(n) + ")"
    # Static Method
    @staticmethod    
    def fibonacci(n):
        Fiborial.__staticCount += 1  
        print "\nFibonacci(" + str(n) + ")"

def main():
    # Calling Static Constructor and Methods    
    # No need to instantiate    
    Fiborial.fibonacci(5)  
      
    # Calling Instance Constructor and Methods    
    # Instance required    
    fib = Fiborial()    
    fib.factorial(5)  

    Fiborial.fibonacci(15)  
    fib.factorial(5)  
      
    # Calling Instance Constructor and Methods    
    # for a second object    
    fib2 = Fiborial()  
    fib2.factorial(5)  
      
    print ""  
    # Calling Static Property
    # using the static method referenced by the property
    #print "Static Count =", Fiborial.StaticCount
    print "Static Count =", Fiborial.getStaticCount()
    # Calling Instance Property of object 1 and 2    
    print "Instance 1 Count =", fib.InstanceCount
    print "Instance 2 Count =", fib2.InstanceCount
      
    sin = Scanner(System.in)    
    line = sin.nextLine()    
    sin.close()
  
if __name__ == '__main__':
    main()

And the Output is:























Factorial using int, float, java.math.BigInteger

So, it looks like integers in python can hold big integers, so using Jython int/long or java.math.BigInteger is the same so not much to say here.


import java
from java.util import Scanner
from java.math import BigInteger
from java.lang import System 
import Stopwatch

# Int/Long Factorial  
def factorial_int(n):  
    if n == 1:
        return int(1)
    else:  
        return int(n * factorial_int(n - 1))
      
# double/float Factorial
def factorial_float(n):
    if n == 1:
        return float(1.0)
    else:  
        return float(n * factorial_float(n - 1))

# BigInteger Factorial     
def factorial_bigint(n):
    if n == 1:
        return BigInteger.ONE
    else:
        return BigInteger.valueOf(n).multiply(factorial_bigint(n-1))
  
timer = Stopwatch()  
facIntResult = 0
facDblResult = 0.0  
facBigResult = BigInteger.valueOf(0)
i = 0  
      
print "\nFactorial using Int/Long"
# Benchmark Factorial using Int64    

for i in range(5,55,5):  
    timer.start()
    facIntResult = factorial_int(i)
    timer.stop()          
    print " (" + str(i) + ") =", timer.elapsed, " :", facIntResult  
      
print "\nFactorial using Float/Double"  
# Benchmark Factorial using Double  
for i in range(5,55,5):
    timer.start()  
    facDblResult = factorial_float(i)  
    timer.stop()          
    print " (" + str(i) + ") =", timer.elapsed, " :", facDblResult
      
print "\nFactorial using BigInteger"  
# Benchmark Factorial using BigInteger  
for i in range(5,55,5):  
    timer.start()
    facBigResult = factorial_bigint(i)  
    timer.stop()
    print " (" + str(i) + ") =", timer.elapsed, " :", facBigResult    

sin = Scanner(System.in)    
line = sin.nextLine()    
sin.close()

And the Output is: