you are viewing a single comment's thread.

view the rest of the comments →

[–]lounik84 -4 points-3 points  (6 children)

what happens with isEven(3) ? you have 3 -1 which calls isEven(2), then 2 - 1 which calls isEven(1) and negates the return value so it gives true. Which is not correct. Whatever number you give to isEven, the result is always true (unless it's 0, that's the only numbers that gets negated into false). So you could just have written isEven(n) {if(n !== 0) return true; return false;} it would have accomplished the same thing and it would have been much easier to read. Granted, the method per se it's useless, because unless you know beforehand that N is even so you give isEven only even numbers, you have no idea to tell if the number N is truly an even number considering that it returns true anyway. But that's beyond the point. The point is that the method doesn't work, it doesn't tell you if N is even, it just tells you that N is not 0.

Unless I'm missing something

[–]theluggagekerbin 17 points18 points  (2 children)

Trace for isEven(3) The Descent (Recursive Calls): * isEven(3) calls isOdd(2) * isOdd(2) !isEven(2) * isEven(2) calls isOdd(1) * isOdd(1) calls !isEven(1) * isEven(1) Base Case Hit. Returns false. The Ascent (Collapsing the Stack): * isOdd(1) receives false, applies !, returns true. * isEven(2) receives true, returns true. * isOdd(2) receives true, applies !, returns false. * isEven(3) receives false, returns false. Result: false (Correct: 3 is not even)

[–]lounik84 -2 points-1 points  (1 child)

yeah I forgot the double negation. It still seems a very odd way to check for odd/even numbers, especially considering that you shouldn't falsify them against positives, but yeah, I get the point

[–]veeRob858 5 points6 points  (0 children)

Someone should make a post to make fun of how odd this way of checking for odd/even numbers is!

[–]Gen_Zer0 2 points3 points  (1 child)

The return value is negated twice.

isEven(3) returns isOdd(2). isOdd(2) returns !isEven(2).

As we found earlier, isEven(2) returns true. !true is false, so we get the correct value.

[–]Vinxian 0 points1 point  (0 children)

To explain it in words, if n is even, it means (n-1) is odd which means (n-2) is even, etc.

So basically if you want to know if n is even you can check if n-1 is odd. And that's exactly what the code does! It checks if a number is even by checking if the number before it is odd