CSP 20-21 U7L07 Level 04

Hello, I think there’s an issue with the solution code in U7 L07 Level 04:

Link to the project or level: This link is to code.org’s solution example:
https://studio.code.org/projects/applab/JEmsWD7dpcEnLbJvZRT-AKtGL2aKK_poF1wPcHaNMnQ/view
What I expect to happen: “-5 is odd?” should return true, -5 is an odd number and -5%2 equals 1.
What actually happens: “-5 is odd?” returns false instead.
What I’ve tried: The solution code works for the other test cases, just not for -5, and the function formula (number%2) == 1 is correct mathematically.

Thank you in advance.

From the ECMAScript 5.1 definition “The sign of the result equals the sign of the dividend.” Meaning that -5 % 2 will be -1 as per the language specification.

So that means there is a bug in the solution. Here is one of many possible fixes :

function isOdd (number) {
  return number % 2 == 1 || number % 2 == -1;
}

Another:

function isOdd (number) {
  return Math.abs(number % 2) == 1;
}

You should open a bug report.

This would work too

function isOdd(number) {
    return !!(number%2)
}

Number%2 will always return 0 if it’s even
Since 0 is the only number that is falsy, anything odd would be truthy. The not not operator will convert it to a boolean.

Another very short solution is

function isOdd(number){
    return number%2!=0
}

Excellent, thank you Don for the fast and on-target reply. Keep up the good support, makes a big difference for teachers like me taking up this new course.

Excellent, thank you for the fast and on-target reply, those are clever solutions. Keep up the good support, makes a big difference for teachers like me taking up this new course.

Hi Everyone,

Thanks for the teamwork here! This has been fixed and it will be live online in the next day or two!

Kaitie