home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / rpos2101.zip / FACT.P < prev    next >
Text File  |  1998-07-02  |  1KB  |  48 lines

  1. R: fact.p - A recursive PILOT program for solving factorials
  2.  : Written by Rob Linwood (auntfloyd@biosys.net)
  3.  
  4. R: A factorial of number n is written as n!  It is the equal to the expression
  5.  : n! = n * (n-1) * (n-2) * (n - 3) * ... * (n - (n-1))
  6.  : For example, 4! = 4 * 3 * 2 * 1 = 24.  The way we solve this in PILOT is to
  7.  : use a programming technique called "recursion".  In a recursive program,
  8.  : one part of the program (generally a subroutine) calls itself.  This a 
  9.  : powerful technique which is crucial in handling numerical sequences.  Note
  10.  : that this is a simple example of recursion, but a useful one.
  11.  
  12. T: Give me a number, please
  13. A: #num
  14.  
  15. R: If #num is 0, 1, or 2, we don't need to solve.  Instead, we go straight to
  16.  : the end.
  17.  : These are "special cases" which can be handled more quickly than others
  18. J( #num = 0 ): zero
  19. J( #num = 1): one
  20. J( #num = 2): two
  21.  
  22. R: Initialize the result (#res) to 0
  23. C: #res = #num
  24.  
  25. *bang
  26. J( #num = 1 ): done
  27. C: #tmp = #num - 1
  28. C: #res = #tmp * #res
  29. C: #num = #num -1
  30. J: bang
  31.  
  32. *zero
  33. T: The answer is Zero
  34. E:
  35.  
  36. *one
  37. T: The answer is One
  38. E:
  39.  
  40. *two
  41. T: The answer is Two
  42. E:
  43.  
  44. *done
  45. T: The answer is #res
  46.  
  47.  
  48.