javascriptfunctionrecursiontaylor-series

Recursive function exponential function


I need implement recursive function exponential function (e^x) with help row Taylor: e^x = 1 + x + x2/2! + x3/3! + ... But i can't understand what i do wrong I have next code:

function fact(n){
    return n * fact(n - 1);
}

function myPow(x, n){
    return x * myPow(x, n - 1);
}

function expon(x ,n){
    if(n == 1){
        return expon(x, n - 1) * x;
    }
    else{
        return expon(x, n - 1) + (myPow(x, n)/fact(n));
    }

}

console.log(expon(1, 10));

Solution

  • Your code should look like this:

    function fact(n){
      if (n == 1)
        return 1;
      return n * fact(n - 1);
    }
    
    function myPow(x, n){
      if(n == 1)
        return n;
      return x * myPow(x, n - 1);
    }
    
    function expon(x ,n){
      if(n == 1){
        return 1;
      }
      else{
        return expon(x, n - 1) + (myPow(x, n)/fact(n));
      }
    
    console.log(expon(1, 10));