Newer
Older
zweic / examples / Factorial.zwei
@glproj03 glproj03 on 22 Nov 2005 781 bytes Added new Factorial.zwei
  1. class Factorial {
  2.  
  3. // Recursive definition
  4. Int factorial1(Int x) {
  5. return if (x == 0) 1
  6. else x * this.factorial1(x - 1)
  7. }
  8.  
  9. // Tail-recursive definition
  10. Int factorial2_aux(Int x, Int acc) {
  11. return if (x == 0) acc
  12. else this.factorial2_aux(x - 1, acc * x)
  13. }
  14. Int factorial2(Int x) {
  15. return this.factorial2_aux(x, 1)
  16. }
  17.  
  18. // Iterative definition
  19. Int factorial3(Int x) {
  20. Int p = 1;
  21. while (x > 0) {
  22. p = p * x;
  23. x = x - 1;
  24. }
  25. return p
  26. }
  27.  
  28. }
  29.  
  30. class Example {
  31. Null main() {
  32. Factorial fac = new Factorial();
  33. Int x = 5;
  34. printInt(fac.factorial1(x));
  35. printChar(10);
  36. printInt(fac.factorial2(x));
  37. printChar(10);
  38. printInt(fac.factorial3(x));
  39. printChar(10);
  40. }
  41. }
  42.  
  43. new Example().main()