Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive even function issue with understanding (Javascript)

The problem is very simple, I have a function from 'Javascript Allonge' book, and having a hard time in understanding it.

The function is called even, and it's as follows:

var even = function(num) {
    return (num === 0) || !(even(num -1));
}

it checks whether the number is even or not, but I do not understand how. It calls itself recursively, and technically, always reaches zero, no? How does that work?

like image 845
Maciej Sitko Avatar asked Aug 19 '15 15:08

Maciej Sitko


People also ask

Can you do recursive functions in JavaScript?

Introduction to the JavaScript recursive functionsThe recurse() is a recursive function if it calls itself inside its body, like this: function recurse() { // ... recurse(); // ... } Generally, you use recursive functions to break down a big problem into smaller ones.

Can JavaScript handle recursion?

In this tutorial, you will learn about recursion in JavaScript with the help of examples. Recursion is a process of calling itself. A function that calls itself is called a recursive function.

How do you recursively check if a number is even?

You can just use let odd = (num%2 == 0) or return (n%2 == 0) without using the conditional operator.

Why do recursive functions result into slower execution?

Recursion has a large amount of overhead as compared to Iteration. It is usually much slower because all function calls must be stored in a stack to allow the return back to the caller functions.


2 Answers

This is based on an inductive definition of numbers being odd or even - a number, n is 'even' when the number before it, n - 1 is odd. This thinking naturally makes sense - 4 is even if 3 is odd.

And so the function even is defined as:

1. even(0) is true - because 0 is even

2. even(n) is the negation of even(n - 1)

Another way to think of it is imagine even(4) being called step by step. By hand, replace the even(4) with result of evaluation it with your function:

even(4)
= !(even(3))
= !(!even(2))
= !(!(!even(1))
= !(!(!(!even(0)))
= !(!(!(!true))
= true


// ...even(4) == true
like image 161
Mahout Avatar answered Oct 19 '22 12:10

Mahout


Well, divide and conquer.

First of all you have two expressions to calculate. The first one is just stopping the recursion at the point when the number is 0, this is easy.

The second expression

!(even(num -1))

is a bit more complicated. It always starts with a call even(num -1) and then negates it.

For the first element !(even(num -1) === true), so now you see that for every second element starting from 1 (1, 3, 5 etc.) it will return false, for others the inverted value.

like image 40
smnbbrv Avatar answered Oct 19 '22 12:10

smnbbrv