Newer
Older
zweic / tests / 3 / 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) {
  12. acc;
  13. } else {
  14. this.factorial2_aux(x - 1, acc * x);
  15. }
  16. }
  17. Int factorial2(Int x) {
  18. return this.factorial2_aux(x, 1)
  19. }
  20.  
  21. // Iterative definition
  22. Int factorial3(Int x) {
  23. Int p = 1;
  24. while (x > 0) {
  25. p = p * x;
  26. x = x - 1;
  27. }
  28. return p
  29. }
  30.  
  31. }
  32.  
  33. class Example {
  34. Null main() {
  35. Factorial fac = new Factorial();
  36. Int x = 5;
  37. printInt(fac.factorial1(x));
  38. printChar(10);
  39. printInt(fac.factorial2(x));
  40. printChar(10);
  41. printInt(fac.factorial3(x));
  42. printChar(10);
  43. }
  44. }
  45.  
  46. new Example().main()