A
A
Alexander Ampleev2014-10-15 16:40:51
JavaScript
Alexander Ampleev, 2014-10-15 16:40:51

Why is parity minus one not defined?

habrahabr.ru/post/240349 - in this article on Habré there is a task of writing a recursive function that returns the parity of a number ..
The code actually from their example is this

function isEven(n) {
  if (n == 0)
    return true;
  else if (n == 1)
    return false;
  else if (n < 0)
    return isEven(-n);
  else
    return isEven(n - 2);
}

if you pass -1 as a parameter, then it returns undefined... I was able to fix it - just a separate conditional case, but I did not understand the causes of the problem ..

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Pushkarev, 2014-10-15
@Ampleev

console.log(-1 % 2); // => -1
console.log(-3 % 2); // => -1

G
Glueon, 2014-10-15
@Glueon

The code looks correct. How was the work checked?

function isEven(n) {
  if (n == 0)
    return true;
  else if (n == 1)
    return false;
  else if (n < 0)
    return isEven(-n);
  else
    return isEven(n - 2);
}

alert( isEven('-1') )ж

Prints false as it should.

D
Dmitry, 2014-11-19
@Zverushko123

cycling

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question