+ 3

Even Odd Program

Is it possible to write a program in javascript which can take the number as input and output whether it's even or odd But wait you can't use any type of conditional statement (no if else, no switch case). Yes or No... If yes write it down below..... No chatGpt or any AI assistance.

17th Jan 2025, 8:34 AM
Mustafa Raza
9 Réponses
+ 2
Zvi For numbers, the binary representation always has 0 as last digit for even numbers and 1 as last digit for odd numbers. So doing a bitwise AND comparison to 1(n & 1) is checking if the last binary digit is 1 (TRUE) or not (FALSE). So "prompt() & 1" will ask user for input and return either FALSE if even, or TRUE if odd. To convert that FALSE/TRUE into "even"/"odd", the key trick is remembering that boolean FALSE also represented as 0, and boolean TRUE represented as 1. You can use that 0 or 1 as index values for an array. ['even', 'odd'] [0] returns 'even' ['even, 'odd'] [1] returns 'odd'
19th Jan 2025, 5:05 AM
Shardis Wolfe
+ 7
0 and 1 can also be used as index of a list or array. so we are not using switch case or if-else... n & 1 works like n % 2 bitwise & 1 will be 1 if it's odd and 0 if it's even. it's supposed to be more efficient than % here is a link for other ways of odd-even ckecking with bitwise operators: https://www.geeksforgeeks.org/check-whether-given-number-even-odd/ so you can write: console.log(['even', 'odd'][prompt() & 1])
17th Jan 2025, 11:07 AM
Bob_Li
Bob_Li - avatar
+ 4
Mustafa Raza Modified Bob_Li's code a little bit. console.log(['even','odd'][prompt()%2]);
17th Jan 2025, 2:01 PM
Gulshan Mahawar
Gulshan Mahawar - avatar
+ 4
Zvi I appreciate the way Bob_Li solved the problem easily, I just posted similar code for easy understanding. Actually he used input & 1, means return 0 if input is even and 1 if odd bcoz all odd number's binary value ends with 1 and all even number's binary value ends with 0.So, 0&&1 is 0 and 1&&1 is 1, in this way indexing works here.
18th Jan 2025, 12:58 AM
Gulshan Mahawar
Gulshan Mahawar - avatar
+ 2
Arash Amorzesh the OP said not to use any type of conditional statement, you used a tenerary operator which is probably against the rules.
17th Jan 2025, 1:51 PM
Zvi
Zvi - avatar
+ 1
Gulshan Mahawar actually I think Bob_li’s solution is way cooler. I had to ask chatGTP to explain it and I still only get the basic idea!
17th Jan 2025, 5:53 PM
Zvi
Zvi - avatar
+ 1
Yes, we can store the condition value to a variable
19th Jan 2025, 7:56 AM
Jatin Singh
Jatin Singh - avatar