Factorial Calculator

A simple script to calculate the factorial of a number entered by the user.

  1. // ==UserScript==
  2. // @name Factorial Calculator
  3. // @namespace http://example.com/factorialcalculator
  4. // @version 1.0
  5. // @description A simple script to calculate the factorial of a number entered by the user.
  6. // @author Your Name
  7. // @match *://*/*
  8. // @license MIT
  9. // @grant none
  10. // @locale en
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15.  
  16. /**
  17. * This function calculates the factorial of a given number 'n'.
  18. * The factorial of a number is the product of all positive integers less than or equal to 'n'.
  19. * For example:
  20. * - factorial(5) = 5 * 4 * 3 * 2 * 1 = 120
  21. * - factorial(0) = 1 (by definition)
  22. *
  23. * @param {number} n - The number to calculate the factorial of. Must be a non-negative integer.
  24. * @returns {number} The factorial of the input number 'n'.
  25. * @throws {Error} If the input 'n' is negative, as factorial is only defined for non-negative integers.
  26. */
  27. function factorial(n) {
  28. if (n < 0) {
  29. throw new Error('Input must be a non-negative integer.');
  30. }
  31. let result = 1;
  32. for (let i = 1; i <= n; i++) {
  33. result *= i;
  34. }
  35. return result;
  36. }
  37.  
  38. // Example usage:
  39. // Prompt the user to enter a number
  40. let num = parseInt(prompt('Enter a non-negative integer:', ''), 10);
  41. // Ensure valid input and display result
  42. if (!isNaN(num) && num >= 0) {
  43. alert('The factorial of ' + num + ' is ' + factorial(num));
  44. } else {
  45. alert('Please enter a valid non-negative integer.');
  46. }
  47. })();