factorial.awl 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. ORGANIZATION_BLOCK OB 1
  2. BEGIN
  3. CALL FC 1 (
  4. N := 0,
  5. RET_VAL := MD 0,
  6. )
  7. __ASSERT== MD 0, L#1
  8. CALL FC 1 (
  9. N := 1,
  10. RET_VAL := MD 0,
  11. )
  12. __ASSERT== MD 0, L#1
  13. CALL FC 1 (
  14. N := 2,
  15. RET_VAL := MD 0,
  16. )
  17. __ASSERT== MD 0, L#2
  18. CALL FC 1 (
  19. N := 3,
  20. RET_VAL := MD 0,
  21. )
  22. __ASSERT== MD 0, L#6
  23. CALL FC 1 (
  24. N := 4,
  25. RET_VAL := MD 0,
  26. )
  27. __ASSERT== MD 0, L#24
  28. CALL FC 1 (
  29. N := 5,
  30. RET_VAL := MD 0,
  31. )
  32. __ASSERT== MD 0, L#120
  33. CALL FC 1 (
  34. N := 6,
  35. RET_VAL := MD 0,
  36. )
  37. __ASSERT== MD 0, L#720
  38. CALL FC 1 (
  39. N := 7,
  40. RET_VAL := MD 0,
  41. )
  42. __ASSERT== MD 0, L#5040
  43. CALL FC 1 (
  44. N := 8,
  45. RET_VAL := MD 0,
  46. )
  47. __ASSERT== MD 0, L#40320
  48. CALL FC 1 (
  49. N := 9,
  50. RET_VAL := MD 0,
  51. )
  52. __ASSERT== MD 0, L#362880
  53. CALL FC 1 (
  54. N := 10,
  55. RET_VAL := MD 0,
  56. )
  57. __ASSERT== MD 0, L#3628800
  58. CALL FC 1 (
  59. N := 11,
  60. RET_VAL := MD 0,
  61. )
  62. __ASSERT== MD 0, L#39916800
  63. CALL FC 1 (
  64. N := 12,
  65. RET_VAL := MD 0,
  66. )
  67. __ASSERT== MD 0, L#479001600
  68. CALL SFC 46 // STOP CPU
  69. END_ORGANIZATION_BLOCK
  70. FUNCTION FC 1 : DINT
  71. TITLE = Calculate the factorial of #N
  72. VAR_INPUT
  73. N : INT;
  74. END_VAR
  75. VAR_TEMP
  76. N_TMP : INT;
  77. R_TMP : DINT;
  78. END_VAR
  79. BEGIN
  80. // If #N is 0 or 1, #RET_VAL is 1 and recursion ends.
  81. L #N
  82. L 1
  83. T #RET_VAL
  84. <=I
  85. BEB
  86. // Subtract 1 from #N
  87. -I
  88. T #N_TMP
  89. // Recurse: Calculate (#N - 1)!
  90. CALL FC 1 (
  91. N := #N_TMP,
  92. RET_VAL := #R_TMP,
  93. )
  94. // Multiply: (#N - 1)! * #N
  95. L #R_TMP
  96. L #N
  97. *D
  98. T #RET_VAL
  99. BE
  100. END_FUNCTION