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));
Your factorial function has no base case.
function fact(n) {
if (n == 1)
return 1;
if (n < 1)
return 0;
return n * fact(n - 1);
}
A similar change will be needed for myPow
. Although since powers are funny, I think if n == 0 return 1.
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));
This looks like an assignment so I won't debug your code but give you some hints.
You seem to not understand how recursion ends with giving a result in the end.
You have to provide a simple case where you return a value with a non recursive call.
Sometimes you don't write any if
(bad!), and sometimes there is an if
, but both cases use a recursive call.
This will solve your problem:
function fact(n) {
if (n == 1) return 1;
return n * fact(n - 1);
}
function myPow(x, n) {
if (n == 0) return 1;
return x * myPow(x, n - 1);
}
function expon(x, n) {
if (n == 0) return 1;
return expon(x, n - 1) + myPow(x, n) / fact(n);
}
console.log(expon(1, 10));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.