JavaScript Factorial Calculator | Finding Factorial Of A Number

How To Find factorial using JavaScript factorial function?

Do you know “What is JavaScript Factorial and how to calculate it“? Imagine a world where numbers have an important part in unlocking infinite possibilities. JavaScript factorial takes center stage, helping the developers to calculate the factorial of any number.  In this tutorial, we will try to find 52 factorial, zero factorial, and 20 factorial along with the basic process to find the factorial of a number.

Still, if you have any doubts related to JavaScript homework then you can hire the best experts from CodingZap.

What is Factorial? Read Below

 

Factorial is a concept that comes from Mathematics. In Mathematics, we all know about the Permutation & Combination concept. Getting the factorial of a number belongs to that section of Mathematics. 

We can say it is a series of multiplication of numbers. In mathematics, the factorial of an integer x is the product of all positive integers less than equal to x, where x is a natural number.

Getting an issue to understand the direct principle of the factorial theory? Let us have a look at the following logic.

Factorial logic: let the number be x. Therefore, x!= x(x-1)*(x-2)*(x-3)*….*1

For example, the factorial of 5! is 120. By definition 5!=5*4*3*2*1=120

 

Let’s write a function for JavaScript factorial:

 

Let’s define a function that accepts a number and calculates its factorial.

 

// function to calculate the factorial of a number using javascript

function factorial(y) {

   var num=0,i=0,fact=1;// variables

    num=y; 

    for(i=1;i<=num;++i){//for loop from 1 to less than the x value.

        fact=fact*i;    //logic   

    };

    console.log(fact); //output on console.

}

We can pass any value to the function by calling it.  You can put any positive value to the variable x to calculate the factorial of a number.

 

// assign a value to x for finding the factorial of a number using javascript

var x=5;

//pass the value of x to the function factorial by calling it.

factorial(x);
Let’s assign 5 to x to find 5 factorials and test the function.
The output of 5 factorials on the console-

 

5 factorials in JavaScript Output
As you can see that the JavaScript factorial function which we built is working fine.
Steps Of The Program to Write a Function for JavaScript Factorial:
  • The above two code snippets need to be cleared before we move ahead. It is confirmed that the program is running fine, but the statements of the program should be discussed properly before moving ahead.
  • In the first code snippet, the factorial function has been declared in JavaScript.Inside that new function, some local variables have been declared & assigned some values.
  • Then, a for loop will be executed from 1 until the appearance of the input number. In each iteration of the for loop, the series of numbers will be multiplied from 1.
  • In the end, the value will be printed using the console log.
  • In the lower code snippet, the process to provide user input will develop in the program. One integer value will be provided that will be shared as an argument value to the function.

Now, we have used the iteration method to implement the factorial of a number. But the same thing can be implemented using the Recursive function also. So, let us have a look there. Apart from JavaScript, you must be learning HTML and CSS courses. But solving HTML & CSS assignments could be challenging and in this case, you can ask for HTML assignment help.

 

How To Find factorial using JavaScript factorial function?

 

As a result, the function works fine till the value of x=21 but fails once we go beyond the x value greater than 21.

For example, let’s find the factorial of 22  using the above function.

factorials of 22 in JavaScript
Have a look at the output above where we try to find the factorial of x=22 which is greater than 21.
Furthermore, you can see that the output of factorial 22! should be 1.1240007277776077e+21 but the actual answer should be 1124000727777607680000.
Doesn’t it seem like a crazy move by JavaScript? Is there any problem we are making? Or it is the default JavaScript problem? Let us try to know it. 
Also, while studying Python it’s important for the programmer to declare the data type before declaring one variable. And, this is done using type conversion.

 

Why the JavaScript factorial function is not giving the correct answer?

 

Our factorial logic is correct so it must have some problem with JavaScript for storing very large values.
Why the JavaScript factorial function is not giving the correct answer?
Here is the reason why-
  1. JavaScript Numbers are Always 64-bit Floating Point

    In other programming languages, we find a large set of numbers. Like, integer numbers, float numbers, double numbers, etc. But inside JavaScript, there is no such large set of numerical data. Here in case of the JavaScript, all numbers are assumed as double precision numbers.

    So, one can face such issues while using JavaScript programming language. It is not the fault of the developer, but a problem with the compiler. That is the reason; we are getting issues while counting the factorial of N numbers.

  2. Integers (numbers without a period or exponent notation) are accurate up to 15 digits

    Another major issue, in this case, is the integer precision problem of JavaScript. In JavaScript, only 15 digits are allowed in any integer variable. If any integer variable has up to 15 digits element, it will work normally. Having more digits, it will start malfunctioning.

    Sometimes, the decimal value goes to 17 digits, if there is more than 15 digits are present in any number. So, these are the key factors we should consider while doing factorial of N numbers.

So, let’s find an alternative approach as we are not satisfied with the result for a greater value of x.

I found a great article and approach to this problem by Niel Patel. Niel has beautifully explained the approach as solved this challenging problem.

function extraLongFactorials(n) {

    let fact = 1;

    for (let i = 2; i <= n; i++){

        if(Number.isSafeInteger(fact*i)){

            fact = fact * i;

        }

        else {

            //fact = fact + fact + .. i times

            let factxi = "0";  // this is (fact * i) for us.

            for(let j = 0; j < i; j++){

                factxi = add(factxi,fact.toString());  

            }

            fact = factxi; // update value of fact before continuing the loop.

        }

    }

    return fact;

}

console.log(extraLongFactorials(25));  // prints 15511210043330985984000000

console.log(extraLongFactorials(34));  // prints 295232799039604140847618609643520000000

The above function makes use of another function which is add():
Steps Of The Program:
  • The above code is nothing but a simple factorial definition in JavaScript. We have followed the simple iteration rule to implement the program. We have made some small changes to the program.
  • Inside of it, we have used isSafeInteger() function. It is used to check the number that is going to use to find whether factorial is safe or not. It checks whether the number is alright to move further or not. If it is Ok, then we will move with the normal iteration method.
  • If the number is not normal, then it will be treated as the string element. And multiplication will be done with the help of another function add(). The implementation of the function is following.
function add(str1, str2) {

    let sum = "";  // our result will be stored in a string.

    // we'll need these in the program many times.

    let str1Length = str1.length;

    let str2Length = str2.length;

    // if s2 is longer than s1, swap them.

    if(str2Length > str1Length ){

        let temp = str2;

        str2 = str1;

        str1 = temp;

    }

    let carry = 0;  // number that is carried to next decimal place, initially zero.

    let a;

    let b;

    let temp;

    let digitSum;

    for (let i = 0; i < str1.length; i++) {

        a = parseInt(str1.charAt(str1.length - 1 - i));      // get ith digit of str1 from right, we store it in a

        b = parseInt(str2.charAt(str2.length - 1 - i));      // get ith digit of str2 from right, we store it in b

        b = (b) ? b : 0;                                    // make sure b is a number, (this is useful in case, str2 is shorter than str1

        temp = (carry + a + b).toString();                  // add a and b along with carry, store it in a temp string.

        digitSum = temp.charAt(temp.length - 1);            //

        carry = parseInt(temp.substr(0, temp.length - 1));  // split the string into carry and digitSum ( least significant digit of abSum.

        carry = (carry) ? carry : 0;                        // if carry is not number, make it zero.
Steps Of The Program:
  • At first, we should take two different numbers in the string format as the argument of the function.
  • Now, the length of each string will be calculated. And the string which is longer will be kept on the top & the smaller one will be kept low to that. If needed, we have to do some swapping of the strings.
  • Now, one for loop will be implemented & the for loop will work on the longest string data. Each & every digit of both strings will be calculated. And as per the need of the calculation, the carry should be marked.
  • After every iteration, the leftmost element will be added to the ‘Sum’ string. And the remaining one will be added to the ‘Carry’ string. Here, we should note that the ‘Sum’ string is the return variable.
  • At the end of the program, the need to use the ‘Carry’ will be finished. The work will be done on the ‘Sum’ part. The sum will be the result of the add() function.
Factorial Calculator:

Also, I have made the JavaScript factorial calculator using the codes I mentioned above.

Kindly use this factorial calculator to find the factorial of any positive number.

Hence, This calculator can calculate the factorial of large numbers such as 52 factorial, zero factorial, and 20 factorial.

What is 52 factorial?

52 factorial is 80658175170943878571660636856403766975289505440883277824000000000000

The JavaScript factorial program works fine though the factorial of 52 is a significantly large value.

What is zero factorial?

factorial of 0 is 1

Why zero factorial is 1?

Zero factorial is 1 because by recursive definition of factorial i.e  x!=(x+1)!/(n+1)

As a result, after initializing x with 0 we get the factorial of 0 as 0!=(0+1)!/(0+1).. i.e=1.

What is 20 factorial?

Similarly, let’s find the 20 factorials using the factorial calculator which I have made using JavaScript.

20 factorial is  2432902008176640000.

Go ahead and try with a different number, use the factorial calculator.

 

Closing Notes:

 

Finally, thanks for reading, if the tutorial was helpful to you feel free to comment, and don’t forget to share.

if you are working towards becoming a better JavaScript developer you can read javascript and jquery.

So, hope you have liked this piece of article. Share your thoughts in the comments section and let us know if we can improve more. Contact us for JavaScript Homework Help

Leave a Comment

Your email address will not be published. Required fields are marked *