Advertisement
Guest User

Factorial Calculator

a guest
Oct 9th, 2018
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //////////////////////////////////////////////////////////////////////////
  2. // Written by M.Quartz of Second Life. Mon Oct 8, 2018: This script
  3. // calculates the factorial sum of a chosen integer using a recursion
  4. // method instead of a loop.
  5. //
  6. // https://en.wikipedia.org/wiki/Triangular_number
  7. //
  8. //////////////////////////////////////////////////////////////////////////
  9. // Recursive functions hog memory and can heap collide very quickly
  10. // especially with lsl scripts capped at 64k. So limit the input to
  11. // avoid memory problems.
  12. #define LIMIT       1600
  13.  
  14. //////////////////////////////////////////////////////////////////////////
  15. #define int         integer
  16. #define str         string
  17. #define rtn         return
  18.  
  19. #define print(a)    llSay(0, a)
  20.  
  21. //////////////////////////////////////////////////////////////////////////
  22. #define RCT         "[Recursion Test] "
  23. #define MES1        "Enter a number to calculate it's factorial sum: \n"
  24. #define MES2(a,b)   "Triangular sum of "+a+" = "+b+"\n"
  25. #define ERR(a)      "Triangular sum of "+a+" = E\n"
  26.  
  27. //////////////////////////////////////////////////////////////////////////
  28. // Recursive Function: To simulate
  29. // this 𝚺 Formula: \sum_{x=1}^{n}x!
  30. int x(int n)
  31. {
  32.     if (n <= 1)
  33.         rtn 1;
  34.     else
  35.         rtn n+x(n-1); // Calls on itself
  36. }
  37. //////////////////////////////////////////////////////////////////////////
  38. // Begin Events:
  39. default
  40. {
  41.     state_entry()
  42.     {
  43.         llListen(0, "", llGetOwner(), "");
  44.         print(RCT+MES1);
  45.     }
  46.     listen(int c, str N, key i, str m)  
  47.     {
  48.         int n = (int)m;
  49.  
  50.         if (n > 0 &&
  51.             n < LIMIT) {
  52.                
  53.             str t = (str)x(n);
  54.             print(RCT+MES2(m,t));
  55.         }
  56.         else
  57.             print(RCT+ERR(m)); // Because: 32 bit
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement