Newer
Older
zweic / examples / Factorial.zwei
@glproj03 glproj03 on 20 Nov 2005 789 bytes *** empty log message ***
class Factorial {

  // Recursive definition
  def factorial1(x: Int): Int =
    if (x == 0) 1
    else x * this.factorial1(x - 1);

  // Tail-recursive definition
  def factorial2_aux(x: Int, acc: Int): Int =
    if (x == 0) acc
    else this.factorial2_aux(x - 1, acc * x);
  def factorial2(x: Int): Int =
    this.factorial2_aux(x, 1);

  // Iterative definition
  def factorial3(x: Int): Int = {
    var p: Int = 1;
    while (x > 0) {
      set p = p * x;
      set x = x - 1;
    }
    p
  };

}

class Example {
  def main(): Null = {
    var fac: Factorial = new Factorial();
    var x: Int = 5;
    printInt(fac.factorial1(x));
    printChar(10);
    printInt(fac.factorial2(x));
    printChar(10);
    printInt(fac.factorial3(x));
    printChar(10);
  };
}

new Example().main()