Search code examples
javascripttestingecmascript-6automated-testsecmascript-5

other text cases for basic function challenge in hackerank


I am trying to solve this hackerrank challenge.The code gives the right solution and passes the basic test case, however, two other test cases fail. If this approach can pass the test we can use another one. Please assist me pass the other test cases thanks in advance. Here is my code:

function factorial(n){
    let myNum = n;
    let res;

    if(myNum === n){
        res = myNum * (n -1);
        myNum = n - 1; 
    }

    if(myNum > 0){
        res = res * (myNum - 1);
        myNum --;
    }
    return res;
}

Solution

  • I don't really like recursion for factorial algorithms.

    while loops work nicely. With factorial the main case is that we are still running equations while n is greater than 0 so 1 is the last number we are going to multiply. This is because we know that once our iteration is 1 we want to stop the algorithm and the last number will remain the factorial.

    function factorial(n){
    var product = 1
    while(n > 0){
        product = product * n
        n = n -1
    }
    return product  
    }
    

    if you are going to do recursion you need to have a base case you need to think of what factorial is the easiest to solve. So factorial(2) is the smallest factorial number. If the factorial is 1 we do not want to do another subtraction because anything times 0 is 0.

    The final equation or the base case will be n * 1.

    So that would be the base case for a recursive algorithm.

    function factorial(n){
       if (n == 1){
        return n
       }else{
         return n * factorial(n -1)
       }
    

    }

    recursion and loops work under similar principles in a loop what is contained between the {} in JS is the code which is run under a certain condition. With recursion we are calling the code as a self contained module in a function. We are manipulating the parameters with the conditions of the functions to create a case where the function will stop. Otherwise we will end up in an infinite loop.