Sum of even numbers from 1-100 using recursive function in Javascript - 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

Related

Trying to understand recursion in JS... check my simple code

I am trying to wrap my head around recursive functions. I've tried a number of entry level exercises with no success. For example, I put this code into JS fiddle. I intended for it to take the sum of all numbers from 1 to n.
function sumAll(n) {
if (n == 1 ) {
return 1;
} else if (n > 1) {
return sumAll(n--) + n;
}
}
console.log(sumAll(3));
feeding 3 to the function should give me '6'. I get an error, though.
The -- suffix operator will evaluate to the original value of n, and the subtraction from n will happen afterwards (which is also not desired as you still want to do + n). That means the recursive call gets the same value for n as the caller, and so you don't get closer to the end...
Don't use -- here, but -1:
function sumAll(n) {
if (n == 1 ) {
return 1;
}
else if (n > 1) {
return sumAll(n-1) + n;
}
}
console.log(sumAll(3));
Perhaps you will enjoy a repeatable technique that can guide you through designing your recursive function. Let's solve sumAll using inductive reasoning -
If n is zero, return the empty sum, zero
(inductive) n is negative or positive. If n is negative, return the negative result of the subproblem sumAll(-n)
(inductive) n is positive. Return n plus the result of the subproblem sumAll(n - 1)
function sumAll(n) {
if (n == 0) // 1
return 0
else if (n < 0) // 2
return -sumAll(-n)
else
return n + sumAll(n - 1) // 3
}
console.log(sumAll(-10), sumAll(0), sumAll(10))
// -55 0 55
Here is sumAll written using a switch instead. It behaves identically but maybe you will find the syntax nicer to read -
function sumAll(n) {
switch (true) {
case n == 0: return 0 // 1
case n < 0: return -1 * sumAll(-n) // 2
default: return n + sumAll(n - 1) // 3
}
}
console.log(sumAll(-10), sumAll(0), sumAll(10))
// -55 0 55
Here is sumAll again as a pure, functional expression -
const sumAll = (n = 0) =>
n == 0 // 1
? 0
: n < 0 // 2
? -1 * sumAll(-n)
: n + sumAll(n - 1) // 3
console.log(sumAll(-10), sumAll(0), sumAll(10))
// -55 0 55

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

powerofTwo algorithm solution

Below is my algo to check if number is a power of two. When I run this algo in test case "2" the answer is false. I want to know why it behaves this way ?
var isPowerOfTwo = function(n) {
if(n === 1){
console.log("i came here");
return true;
}
if(n === 0){
return false;
}
if(n%2 === 0){
console.log(n);
n=n/2;
console.log(n);
isPowerOfTwo(n);
}
if(n%2 === 1){
return false;
}
};
You're not returning the recursive call, and you're also changing n before the tests have finished - if n / 2 resolves to 1 then your reassignment of n will result in the bottom if statement running. Use else instead, and don't reassign n, simply pass n / 2 to the recursive call:
var isPowerOfTwo = function(n) {
if (n === 1) return true;
if (n === 0) return false;
if (n % 2 === 0) return isPowerOfTwo(n / 2);
else return false;
};
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));
Your if (n%2 === 1) return false; condition could result in another bug: what if the initial n was not an integer? Then the function would call itself forever, resulting in an overflow.
Because 1 % 2 === 1
The "problem" is that in the third if you are changing the value of n and not returning any value so it will enter the last if too.
As mentioned, you don't return any value in the 3rd if statement, hence you always get false for values greater than 1 as it will execute the 4th statement too.
In addition to the given answers, here is an interesting solution (initially by Jaromanda X), which I expanded so it deals with if a non-number is passed as a value.
Try cast to a number
const isPowerOfTwo = n => Number(n).toString(2).split('1').length === 2
console.log(isPowerOfTwo(''));
console.log(isPowerOfTwo('0'));
console.log(isPowerOfTwo('1'));
console.log(isPowerOfTwo('2'));
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));
Check the type
const isPowerOfTwo = n => typeof n === 'number' && n.toString(2).split('1').length === 2
console.log(isPowerOfTwo(''));
console.log(isPowerOfTwo('0'));
console.log(isPowerOfTwo('1'));
console.log(isPowerOfTwo('2'));
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));
I think you just need to return an actual value from the n % 2 === 0 branch of your function:
var isPowerOfTwo = function(n) {
if (n === 1) {
console.log("i came here");
return true;
}
else if (n === 0) {
return false;
}
else if (n % 2 === 0) {
console.log(n);
n = n / 2;
console.log(n);
return isPowerOfTwo(n);
}
else { // no need for an if here
return false;
}
};
Note that in the final else we do not need to check anything, because we have already ascertained the number is not a multiple of 2.
Javascript one-liner solution
For any power of 2 (n & n - 1) will return 0. Simple bit-wise operators
isPowerOfTwo = n => !(n & n - 1)
The above function will return true for 0, which is not a power of 2. For that
isPowerOfTwo = n => (n != 0) && !(n & n - 1)

making a factorial in javascript with recursion beginner

function nFactorial(n) {
// return the factorial for n
// example:
// the factorial of 3 is 6 (3 * 2 * 1)
if (n < 0){
return;
}
if (sum === undefined){
sum = 1;
}
sum *= n;
nFactorial(n - 1);
return sum;
}
nFactorial(3);
I'm doing my first stab at learning recursion in javascript. I'm trying to solve a problem where I'm making a factorial. I error I get right now is
ReferenceError: sum is not defined
Can anyone point me in the right direction? I'm feeling a little lost.
For using a product as return value, you could use tail call optimization of the recursion by using another parameter for the product (which replaces the sum in the question).
function nFactorial(n, product) {
product = product || 1; // default value
if (n < 0) { // exit condition without value
return;
}
if (n === 0) { // exit condition with result
return product;
}
return nFactorial(n - 1, n * product); // call recursion at the end of function
}
console.log(nFactorial(3));
This approach minimizes the stack length, because the last call does not extend the stack, as opposite of the standard approach of the following recursion without a product parameter.
function nFactorial(n) {
if (n < 0) {
return;
}
if (n === 0) {
return 1;
}
return n * nFactorial(n - 1);
}
console.log(nFactorial(3));
the way you write your code will result always in 0 , here is the correct way for a factorial with recursion, also you need to check if n is a number or the code will trow an error
const factorial =(n)=> {
if(isNaN(n)){
console.log("enter a number")
return 0
}
if(n === 0) {
return 1
} else {
return n * factorial(n - 1);
}
}
console.log(factorial(5));
A simple implementation:
function factorial(n) {
if (n === 1 || n === 0) {
return n;
}
return n * factorial(n-1);
}

JS:checking if number belongs to Fibonacci sequence(without loop)

Is there an efficient way to check if number belongs to Fibonacci sequence?
I've seen many examples with a loop that creates the sequence in an array and checks every time if newly generated number of the sequence is equal to the input number. Is there another way?
http://www.geeksforgeeks.org/check-number-fibonacci-number/
This link details that there is a special quality about fibonacci numbers that means that a number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square.
So,
function (num) {
if (isSquare(5*(num*num)-4) || isSquare(5*(num*num)+4)) {
return true;
} else { return false; }
}
Then isSquare would just be a simple checking function.
Edit: Worth noting that while this is a much more efficient and easy way to find fibonacci numbers, it does have an upper bound. At about the 70th Fibonacci number and above, you may see issues because the numbers are too large.
function isFibonacci(num, a = 0, b = 1) {
if(num === 0 || num === 1) {
return true;
}
let nextNumber = a+b;
if(nextNumber === num) {
return true;
}
else if(nextNumber > num) {
return false;
}
return isFibonacci(num, b, nextNumber);
}
function isPerfectSquare(n) {
return n > 0 && Math.sqrt(n) % 1 === 0;
};
//Equation modified from http://www.geeksforgeeks.org/check-number-fibonacci-number/
function isFibonacci(numberToCheck)
{
// numberToCheck is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
// is a perferct square
return isPerfectSquare(5*numberToCheck*numberToCheck + 4) ||
isPerfectSquare(5*numberToCheck*numberToCheck - 4);
}
for(var i = 0; i<= 10000; ++i) {
console.log(i + " - " + isFibonacci(i));
}
This will most likely fail for larger numbers though.
def is_squared(number):
temp_root = math.sqrt(number);
temp_root = int(temp_root);
return (temp_root * temp_root == number);
def check_all_fibo(test_number_list):
result_fibo_list = [];
for item in test_number_list:
if item==0 or item == 1 or item == 2:
result_fibo_list.append(item);
continue;
if is_squared(5 * item * item - 4) or is_squared(5 * item * item + 4):
result_fibo_list.append(item);
return result_fibo_list;
this is a python implementation by me. But keep in mind, the formula only works when the fib is not too large.
The Fibonacci sequence is a series of numbers where a number is the addition of the last two numbers, starting with 0, and 1. Th following js function is explaining this.
function isFabonacci(n) {
if (n === 1 || n === 0) {
return true;
}
let firstPrevNumber = n - 1;
let secondPrevNumber = n - 2;
return (firstPrevNumber + secondPrevNumber === n);
}
// isFabonacci(2) -> false
// isFabonacci(3) -> true

Categories

Resources