How to resolve the algorithm Factorial step by step in the JavaScript programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Factorial step by step in the JavaScript programming language

Table of Contents

Problem Statement

Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Factorial step by step in the JavaScript programming language

First Code

The first function, factorial, computes the factorial of a non-negative integer n. It checks if n is negative, and if so, it throws an error. It then initializes result to 1 and multiplies it by n while decreasing n until it reaches 1. Finally, it returns result. The second function, an anonymous function, defines a memoized factorial function that uses the memoization technique to improve performance. It stores the factorial of each number in a JavaScript object called memo and returns the cached value if it exists. If not, it computes the factorial and stores it in memo before returning it.

Second Code

The second code is a functional programming approach using the reduce method of the Array object. It creates a range of numbers from 1 to x using the range function and then reduces this range to a single value by multiplying each element using the reduce function. The factorial function takes the x value and returns the result of reducing the range using the reduce function.

Third Code

The third code uses an arrow function to define the factorial function, which takes an integer n as an argument. It creates an array of numbers from 1 to n using the enumFromTo function and then uses the reduce method to multiply all the numbers together. The product function is defined to perform the multiplication.

Fourth Code

The fourth code is an HTML and JavaScript code that demonstrates the calculation of factorials. It includes buttons to increment the factorial value and to calculate the factorial of a single value entered by the user. The incrementFact function calculates the factorial of a range of numbers and displays the result. The singleFact function calculates the factorial of a single number entered by the user.

Final Code

The final code uses the mathFact function to calculate the factorial of a range of numbers. It uses the reduceRight method to multiply the numbers together and displays the result. It also includes input fields and buttons to allow the user to input a single value and calculate its factorial.

Source code in the javascript programming language

function factorial(n) {
  //check our edge case
  if (n < 0) { throw "Number must be non-negative"; }

  var result = 1;
  //we skip zero and one since both are 1 and are identity
  while (n > 1) {
    result *= n;
    n--;
  }
  return result;
}

(function(x) {

  var memo = {};

  function factorial(n) {
    return n < 2 ? 1 : memo[n] || (memo[n] = n * factorial(n - 1));
  }
  
  return factorial(x);
  
})(18);

6402373705728000

(function () {
    'use strict';

    // factorial :: Int -> Int
    function factorial(x) {

        return range(1, x)
            .reduce(function (a, b) {
                return a * b;
            }, 1);
    }



    // range :: Int -> Int -> [Int]
    function range(m, n) {
        var a = Array(n - m + 1),
            i = n + 1;

        while (i-- > m) a[i - m] = i;
        return a;
    }


    return factorial(18);

})();

6402373705728000

var factorial = n => (n < 2) ? 1 : n * factorial(n - 1);

(() => {
    'use strict';

    // factorial :: Int -> Int
    const factorial = n =>
        enumFromTo(1, n)
        .reduce(product, 1);


    const test = () =>
        factorial(18);
    // --> 6402373705728000


    // GENERIC FUNCTIONS ----------------------------------

    // product :: Num -> Num -> Num
    const product = (a, b) => a * b;

    // range :: Int -> Int -> [Int]
    const enumFromTo = (m, n) =>
        Array.from({
            length: (n - m) + 1
        }, (_, i) => m + i);

    // MAIN ------
    return test();
})();

<html>

  <body>

    <button onclick="incrementFact()">Factorial</button>
    <p id="FactArray"></p>
    <p id="Factorial"></p>
    <br>
    
  </body>

</html>

<input id="userInput" value="">
<br>
<button onclick="singleFact()">Single Value Factorial</button>
<p id="SingleFactArray"></p>
<p id="SingleFactorial"></p>


<script>
  function mathFact(total, sum) {
    return total * sum;
  }

  var incNumbers = [1];

  function incrementFact() {
    var n = incNumbers.pop();
    incNumbers.push(n);
    incNumbers.push(n + 1);
    document.getElementById("FactArray").innerHTML = incNumbers;
    document.getElementById("Factorial").innerHTML = incNumbers.reduceRight(mathFact);

  }

  var singleNum = [];

  function singleFact() {
    var x = document.getElementById("userInput").value;
    for (i = 0; i < x; i++) {
      singleNum.push(i + 1);
      document.getElementById("SingleFactArray").innerHTML = singleNum;
    }
    document.getElementById("SingleFactorial").innerHTML = singleNum.reduceRight(mathFact);
    singleNum = [];
  }

</script>

  

You may also check:How to resolve the algorithm Department numbers step by step in the Prolog programming language
You may also check:How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Gambas programming language
You may also check:How to resolve the algorithm SHA-1 step by step in the PHP programming language
You may also check:How to resolve the algorithm Execute HQ9+ step by step in the Phix programming language
You may also check:How to resolve the algorithm Write language name in 3D ASCII step by step in the Erlang programming language