Recursive function exponential function - javascript

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));

Related

Why is my factorial function returning NaN?

I wrote a factorial function using recursion and a while-loop but it's return value is NaN whenever it is called. Please I want to know why? and how to fix it?
Function
function factorial(n) {
while(n > 0)
return factorial(n - 1) * n;
}
You're missing the return statement for the base case. The function returns undefined when you return without a value, and when you multiply that you get NaN.
Also, you're not looping, so you should use if rather than while.
function factorial(n) {
if (n > 0) {
return factorial(n - 1) * n;
} else {
return 1;
}
}
console.log(factorial(10));
You can also write it with looping instead of recursion.
function factorial(n) {
result = 1;
for (var i = 1; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorial(10));
If you track your recursion, you'll see when n reaches 1, which make n-1 = 0 and the factorial(0) is called, your function does not know what to do next and does not return any number (NaN). That NaN multiplies with all other things returning another NaN.
Add an instruction for your function in to handle n = 0:
function factorial(n) {
if (n == 0) return 1;
while(n > 0)
return factorial(n - 1) * n;
}
Just add the base case n === 0 to n === 1 to end the tail recursion.
console.log(function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return factorial(n - 1) * n;
}(4));
you can also write it in single line:
const factorial = (n) => (n > 1) ? factorial(n-1) * n : 1

JavaScript fibonacci - RangeError: when base (n == 1) or (n == 0), but not if (n <= ). Why?

This works fine:
function fibonacci(n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
console.log('fibonacci ' + fibonacci(7));
But if I replace the base with (n == 1) or (n == 0) or even (n === 1). I get a RangeError. Can somebody explain why? The funny thing is that it works with simple sum function:
function sumTo(n) {
if (n == 1) {
return n;
} else {
return n + sumTo2(n - 1);
}
}
You need both checks of n === 1 || n === 0, because you take the call with two values, n - 1 and n - 2.
function fibonacci(n) {
if (n === 1 || n === 0) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
console.log('fibonacci ' + fibonacci(7));
it should work for n==1 || n==0
function fibonacci(n) {
if (n == 1 || n==0) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
for n===1 it doesnt work
because for n=2 second call will go for n-2 which is0 and thats what you are not handling

Sum of even numbers from 1-100 using recursive function in Javascript

I want to sum even numbers from 1-100 using javascript recursive function, but the output just show me 0 for odd numbers and the number itself for odd numbers
function evenSum(n) {
if (n%2 === 1) {
return 0;
}
else if (n === 100) {
return 100;
}
return n + evenSum(n+1);
}
if (n%2 === 1) {
return 0;
}
That will stop the recursive chain at every second number. For every odd number it will stop directly (and return 0) for every even number it will stop at the second position. Instead, you just want the recursion to continue with the next chain:
if (n%2 === 1) {
return evenSum(n + 1);
}
Actually you can simplify (and speed up the code) if you just go to every second position:
function evenSum(n){
// Stop at 100
if(n >= 100) return 100;
// If it starts at an odd position, go on with the next even
if(n % 2 === 1) return evenSum(n + 1);
// Usually just take every second step:
return n + evenSum(n + 2);
}
That can be shortified to:
const evenSum = n => n >= 100 ? 100 : n % 2 ? evenSum(n + 1) : n + evenSum(n + 2);
You could use a recursion function which count down the values until you reach zero.
The exit condition is a check if the number is smaller or equal to zero, then return the sum otherwise decrement uneven value by one and even value by two and call the function again with the value and temporary sum.
function evenSum(n, s = 0) {
if (n <= 0) {
return s;
}
return evenSum(n - (n % 2 ? 1 : 2), s + n); // tail recursion
}
console.log(evenSum(100));
function evenSum(n) {
if (n <= 1)
return 0;
else
{
if(n%2 === 1)
return evenSum(n - 1);
else
return n + evenSum(n - 1);
}
}
Something like that (works for all numbers, not just 100):
function evenSum(n) {
if (n == 0) return 0; // recursive function needs to stop somewhere
var sum = evenSum(n - 1); // recursive call
if (n % 2 == 0) sum += n; // add current n if it's even
return sum; // return result
}
console.log(evenSum(100));
recursive sum of even number
one line condition
function addOddToN(n) {
return (n <= 2) ? 2 : (n%2 === 0) ? n + addOddToN(n - 1) : addOddToN(n - 1);
}
console.log( addOddToN(100) ); // 2550
console.log( addOddToN(5) ); // 6
console.log( addOddToN(4) ); // 6
console.log( addOddToN(10) ); // 30

How to find nth Fibonacci number using Javascript with O(n) complexity

Trying really hard to figure out how to solve this problem. The problem being finding nth number of Fibonacci with O(n) complexity using javascript.
I found a lot of great articles how to solve this using C++ or Python, but every time I try to implement the same logic I end up in a Maximum call stack size exceeded.
Example code in Python
MAX = 1000
# Create an array for memoization
f = [0] * MAX
# Returns n'th fuibonacci number using table f[]
def fib(n) :
# Base cases
if (n == 0) :
return 0
if (n == 1 or n == 2) :
f[n] = 1
return (f[n])
# If fib(n) is already computed
if (f[n]) :
return f[n]
if( n & 1) :
k = (n + 1) // 2
else :
k = n // 2
# Applyting above formula [Note value n&1 is 1
# if n is odd, else 0.
if((n & 1) ) :
f[n] = (fib(k) * fib(k) + fib(k-1) * fib(k-1))
else :
f[n] = (2*fib(k-1) + fib(k))*fib(k)
return f[n]
// # Driver code
// n = 9
// print(fib(n))
Then trying to port this to Javascript
const MAX = 1000;
let f = Array(MAX).fill(0);
let k;
const fib = (n) => {
if (n == 0) {
return 0;
}
if (n == 1 || n == 2) {
f[n] = 1;
return f[n]
}
if (f[n]) {
return f[n]
}
if (n & 1) {
k = Math.floor(((n + 1) / 2))
} else {
k = Math.floor(n / 2)
}
if ((n & 1)) {
f[n] = (fib(k) * fib(k) + fib(k-1) * fib(k-1))
} else {
f[n] = (2*fib(k-1) + fib(k))*fib(k)
}
return f[n]
}
console.log(fib(9))
That obviously doesn't work. In Javascript this ends up in an infinite loops. So how would you solve this using Javascript?
Thanks in advance
you can iterate from bottom to top (like tail recursion):
var fib_tail = function(n){
if(n == 0)
return 0;
if(n == 1 || n == 2)
return 1;
var prev_1 = 1, prev_2 = 1, current;
// O(n)
for(var i = 3; i <= n; i++)
{
current = prev_1 + prev_2;
prev_1 = prev_2;
prev_2 = current;
}
return current;
}
console.log(fib_tail(1000))
The problem is related to scope of the k variable. It must be inside of the function:
const fib = (n) => {
let k;
You can find far more good implementations here list
DEMO
fibonacci number in O(n) time and O(1) space complexity:
function fib(n) {
let prev = 0, next =1;
if(n < 0)
throw 'not a valid value';
if(n === prev || n === next)
return n;
while(n >= 2) {
[prev, next] = [next, prev+next];
n--;
}
return next;
}
Just use two variables and a loop that counts down the number provided.
function fib(n){
let [a, b] = [0, 1];
while (--n > 0) {
[a, b] = [b, a+b];
}
return b;
}
console.log(fib(10));
Here's a simpler way to go about it, using either iterative or recursive methods:
function FibSmartRecursive(n, a = 0, b = 1) {
return n > 1 ? FibSmartRecursive(n-1, b, a+b) : a;
}
function FibIterative(n) {
if (n < 2)
return n;
var a = 0, b = 1, c = 1;
while (--n > 1) {
a = b;
b = c;
c = a + b;
}
return c;
}
function FibMemoization(n, seenIt = {}) {//could use [] as well here
if (n < 2)
return n;
if (seenIt[n])
return seenIt[n];
return seenIt[n] = FibMemoization(n-1, seenIt) + FibMemoization(n-2, seenIt);
}
console.log(FibMemoization(25)); //75025
console.log(FibIterative(25)); //75025
console.log(FibSmartRecursive(25)); //75025
You can solve this problem without recursion using loops, runtime O(n):
function nthFibo(n) {
// Return the n-th number in the Fibonacci Sequence
const fibSeq = [0, 1]
if (n < 3) return seq[n - 1]
let i = 1
while (i < n - 1) {
seq.push(seq[i - 1] + seq[i])
i += 1
}
return seq.slice(-1)[0]
}
// Using Recursion
const fib = (n) => {
if (n <= 2) return 1;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(4)) // 3
console.log(fib(10)) // 55
console.log(fib(28)) // 317811
console.log(fib(35)) // 9227465

Get sum of sequence using recursion

I have this sum:
Obviously, I have to get sum of that depending on what N is. I need to do it in three different ways.
First is for loop:
function lab(n) {
var S = 0;
let VS
if (n == 0) {
VS = 0;
return 0;
}
if (n == 1) {
VS = 4;
return Math.pow(3 / 5, 1);
} else {
for (let i = 0; i < n; i++) { //
S += 1 / n * Math.pow(3 / 5, n);
t = 4 * n;
}
return S;
}
}
Second one is recursion:
function lab(n) {
let vs = 0;
if (n <= 1)
return 0;
else {
vs += 4 * n // vs is how many actions it takes to make this calculation. I’m sure in for loop this is right, but I’m not sure about the recursion approach
return lab(n - 1) + 1 / n * Math.pow(3 / 5, n)
}
}
The third way is use recursion with the condition that in order to get S(n) I need to use S(n-1).
I am stuck on this.
Also I get different sums with the same Ns from first and second function.
I am not sure what you are asking for.
If you are asking for a recursive function then take a look at the following:
function summation(n, sum = 0) {
if (n <= 0) {
return sum;
}
sum += (1/n) * Math.pow(3/5, n);
return summation(n - 1, sum);
}
console.log(summation(1));
console.log(summation(2));
console.log(summation(3));
console.log(summation(4));
console.log(summation(5));
Another recursive method without passing sum as parameter:
function summation(n) {
if (n <= 0) {
return 0;
}
return ((1/n) * Math.pow(3/5, n)) + summation(n - 1);
}
console.log(summation(1));
console.log(summation(2));
console.log(summation(3));
console.log(summation(4));
console.log(summation(5));
Also, for the loop method, the following will suffice
function summation(n) {
var sum = 0;
while (n > 0) {
sum += (1/n) * Math.pow(3/5, n);
n -= 1;
}
return sum;
}
console.log(summation(1));
console.log(summation(2));
console.log(summation(3));
console.log(summation(4));
console.log(summation(5));

Categories

Resources