Newer
Older
zweic / examples / Factorial.zwei
@glproj03 glproj03 on 22 Nov 2005 781 bytes Added new Factorial.zwei
class Factorial {

  // Recursive definition
  Int factorial1(Int x) {
    return if (x == 0) 1
           else x * this.factorial1(x - 1)
  }

  // Tail-recursive definition
  Int factorial2_aux(Int x, Int acc) {
    return if (x == 0) acc
           else this.factorial2_aux(x - 1, acc * x)
  }
  Int factorial2(Int x) {
    return this.factorial2_aux(x, 1)
  }

  // Iterative definition
  Int factorial3(Int x) {
    Int p = 1;
    while (x > 0) {
      p = p * x;
      x = x - 1;
    }
    return p
  }

}

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

new Example().main()