# Introduction

In number theory, a number is considered evil if there are an even number of 1's in its binary representation. In today's challenge, you will be identifying whether or not a given number is evil.

# Challenge

Your job is to write a full program or function which accepts a single, non-negative integer as input and outputs (or returns) whether or not that number is evil.

• You may output any truthy value if the number is evil, and any falsy value if the number is not evil.
• You may input and output in any acceptable format.
• Standard loopholes are disallowed.
• OEIS sequence A001969 is the sequence containing all evil numbers.
• Here is a list of the first 10000 evil numbers, for reference (and more test cases!)
• This question is , so the shorter, the better.
• Don't be put off by extremely short answers in golfing languages. I encourage you to submit in any language you like.
• Here are some test cases:

3 => True
11 => False
777 => True
43 => True
55 => False
666 => False


At the bottom of the page is a stack snippet containing a leaderboard for this question. (Thanks, @MartinEnder)

# Language Name, N bytes


where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes


If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes


You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes


/* Configuration */

var QUESTION_ID = 169724; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 81420; // This should be the user ID of the challenge author.

/* App */

comment_page;

return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function(data) {
data.items.forEach(function(a) {
});
comment_page = 1;
}
});
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function(data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
});
else process();
}
});
}

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

function getAuthorName(a) {
return a.owner.display_name;
}

function process() {
var valid = [];

var body = a.body;
if (OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});

var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
});
//else console.log(body);
});

valid.sort(function(a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});

var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function(a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;

.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)

var lang = a.language;
lang = jQuery('<a>' + lang + '</a>').text();

languages[lang] = languages[lang] || {
lang: a.language,
lang_raw: lang,
user: a.user,
size: a.size,
};
});

var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);

langs.sort(function(a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});

for (var i = 0; i < langs.length; ++i) {
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
language = jQuery(language);
jQuery("#languages").append(language);
}

}
body {
text-align: left !important;
display: block !important;
}

width: 290px;
float: left;
}

#language-list {
width: 500px;
float: left;
}

font-weight: bold;
}

table td {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<tr>
<td>Language</td>
<td>User</td>
<td>Score</td>
</tr>
<tbody id="languages">

</tbody>
</table>
</div>
<tr>
<td></td>
<td>Author</td>
<td>Language</td>
<td>Size</td>
</tr>

</tbody>
</table>
</div>
<table style="display: none">
<tr>
<td>{{PLACE}}</td>
<td>{{NAME}}</td>
<td>{{LANGUAGE}}</td>
<td>{{SIZE}}</td>
</tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr>
<td>{{LANGUAGE}}</td>
<td>{{NAME}}</td>
<td>{{SIZE}}</td>
</tr>
</tbody>
</table>

EDIT: I believe this question is not a duplicate of this, because whereas that question is asking to count the number of ones, this question is asking whether the number of ones is even. Although you can accomplish this question by simply counting the bits, there are other approaches too.

• Related (XOR-ing every binary digit is the same as taking the sum modulo-2). Aug 1, 2018 at 15:25
• Possible duplicate of Count the number of ones in an unsigned 16-bit integer Aug 1, 2018 at 17:11
• @BetaDecay but that doesn't work in reverse: i.e. you cannot take all of these answers and remove the mod 2. Therefore, this challenge invites some new methods. Aug 1, 2018 at 20:29
• I believe that 666 => False should be a test case. Aug 2, 2018 at 10:38
• Yes, 666 is not evil, but 616 is. More evidence corroborating Papyrus 115! Aug 7, 2018 at 11:41

# Z80 Assembly (8-bit), 2 bytes

The following code only works with values up to 255:

; Input is given in register A.
; P flag is set if A is evil.
B7     or A
C9     ret


# 16-bit version (works on all test cases), 3 bytes

This works with values up to 65535.

; Input is given in BC.
; Output is the same as above.
78     ld A,B
A9     xor C
C9     ret


If you're feeling adventurous, you can shave off 1 byte by storing the input in A and C like so

      ld BC, 777
C5    push BC
F1    pop AF


and then running

A9    xor C
C9    ret


However, this puts the burden on the caller, so it may be that the two bytes (push BC and pop AF) should be counted as well.

• i like this but how does this work? my memory for assembly (6502 + arm) are that ors are bitwise with 2 operands Aug 1, 2018 at 20:00
• @northern-bradley On the Z80, it's implied that the second operand of the or mnemonic is the accumulator A. In this case, the command doesn't change A. It only refreshes the status register (and in particular, the parity flag) to reflect the contents of A. Aug 1, 2018 at 20:04
• Is P allowed as per codegolf.meta.stackexchange.com/a/8509/29560? It's a single bit within the F (flags) register which has only three pairs of instructions affected by it. Also, this answer fails to mention it's only competing for 8-bit values, since A is an 8-bit register. This means it is unable to give an answer for 777, or any other unsigned value over 255. Aug 3, 2018 at 9:51
• Damn built-ins :P
– Jo King
Aug 3, 2018 at 10:04
• @cschultz2048 A is paired with F, so I wouldn't accept AB or BA as a 16-bit value. BC is 16-bit, but then you need an extra instruction to load one of them into A before XORing the other. I've always just mentioned that my Z80 answers work fully up to 255 or 65535, depending on the question. Maybe add a 16-bit version as well? So 2 bytes for 8-bit values, 3 bytes for 16-bit values. Aug 3, 2018 at 13:55

# JavaScript (ES6), 18 bytes

f=n=>n?!f(n&~-n):1


Try it online!

### Explanation

The bitwise logic goes like this:

• For integers, ~-n is equivalent to -(-n)-1, so that just another way of doing n-1. In that particular case, we could actually have used n-1.
• n & (n-1) removes the least significant bit set to 1 in n because decrementing n turns all trailing 0's into 1's and clears the 1 that immediately follows (by carry propagation), while leaving everything else unchanged.

Example for n = 24 (11000 in binary):

  11000 (24)                  11000 (24)
-     1                   AND 10111 (23)
-------                   ---------
= 10111 (23)              =   10000 (16)
^                           ^
|                           |
+--- this bit is cleared ---+


Therefore, we process as many recursive calls as there are 1's in the binary representation of n, inverting the result each time with !. The last call always returns 1.

Examples:

f(24) = !f(16) = !!f(0) = !!1 = true
f(7) = !f(6) = !!f(4) = !!!f(0) = !!!1 = false

• Hello, I understand what the code does, but I just cannot figure out the logic/reasoning behind it, despite having read several articles about bitwise operations, checking if a number is a power of 2, etc. I know what a recursive function is. I just don't get why it has been used this way and why this works to answer to the puzzle, i.e. the link between the recursion and !f(power of two) <==> evil number. If you have time, explanation would be welcome :) thanks! Aug 7, 2018 at 15:34
• @supafly I've added an explanation. And BTW: welcome to PPCG! Aug 7, 2018 at 16:09
• The processing is very clear now. Still, the idea/reasoning is really magic! Thank you for the explanation! Aug 7, 2018 at 16:43

# Python 2, 25 bytes

lambda n:int(bin(n),13)%2


Try it online!

bin(n) gives a result like '0b10101'. Reading this as a base-13 integer, we get

$$\color{red}{11\cdot13^5} + 1\cdot13^4 + 0\cdot13^3 + 1\cdot13^2 + 0\cdot13^1 + 1\cdot13^0$$ which reduces modulo 2 to $$\equiv \color{red}{1 \color{pink}{\cdot 1^5}} + 1 \color{#aaa}{\cdot 1^4} + 0 \color{#aaa}{\cdot 1^3} + 1\color{#aaa}{\cdot 1^2} + 0\color{#aaa}{\cdot 1^1} + 1\color{#aaa}{\cdot 1^0} \pmod 2$$ $$\equiv \color{red}{1}+1+0+1+0+1 \pmod 2.$$

So int(bin(n),13)%2 equals 1 + (number of ones in bin(n)) modulo 2.

If n is evil, then the result is 1; otherwise it is 0.

I picked up this trick from Noodle9.

# Japt -h!, 54 3 bytes

¤å^


Try it

## Explanation

¤       :Convert to base-2 string
å^     :Cumulatively reduce by XORing
:Implicitly output the last element negated

• @LuisfelipeDejesusMunoz, porting Kevin's 05AB1E solution also works out at 5 bytes, if you want to try for that. Aug 1, 2018 at 15:21
• ¤¬x v this is kevin's answer Aug 1, 2018 at 15:28
• @LuisfelipeDejesusMunoz, yup, that's it. Aug 1, 2018 at 15:28

# 05AB1E, 4 bytes

bSOÈ


Explanation:

b       # Convert to binary string
#  i.e. 777 → 1100001001
S      # Change it to a list of 0s and 1s
#  i.e. 1100001001 → ['1','1','0','0','0','0','1','0','0','1']
O     # Take the sum
#  i.e. ['1','1','0','0','0','0','1','0','0','1'] → 4
È    # Check if it's even (1 as truthy, 0 as falsey)
#  i.e. 4 → 1

• Alternatively: b1¢È Feb 8, 2021 at 22:56

# C# (Visual C# Interactive Compiler), 43 38 bytes

Golfed Try it online!

i=>Convert.ToString(i,2).Sum(c=>c)%2<1


Ungolfed

i => Convert.ToString( i, 2 ).Sum( c => c ) % 2 < 1


Full code with tests

Func<Int32, Boolean> f = i => Convert.ToString( i, 2 ).Sum( c => c ) % 2 < 1;

Int32[] testCases = { 3, 11, 777, 43, 55 };

foreach( Int32 testCase in testCases ) {
Console.Write( $" Input: {testCase}\nOutput: {f(testCase)}" ); Console.WriteLine("\n"); } Console.ReadLine();  Releases • v1.1 - -5 bytes - Replaced Count to Sum • v1.0 - 43 bytes - Initial solution. Notes • None • Upvoted for the chuckle your "ungolfed" version gave me. Aug 2, 2018 at 17:02 # Bash (no external utilities), 56 44 bytes while(($1));do set $(($1/2)) $(($2+$1%2));done;!(($2%2)) 

(($1))&&exec$0 $[$1/2] $[$2+$1%2];!(($2%2))


This assumes that the number is found in $1, having been passed as the first command line argument. It also assumes that this is a shell script (so that it can exec itself). It recurses, after a fashion, using exec$0, until the number (in $1) reaches zero, dividing it by two in each iteration. It also sums (in $2) the number of times we get a number that is odd. At the end, the original number was "evil" if the sum in $2 in not odd. Example invocations: $ ./script 3 && echo evil
evil

$./script 11 && echo evil$ ./script 777 && echo evil
evil

$./script 43 && echo evil evil$ ./script 55 && echo evil


For 0:

$./script 0 && echo evil ./script: line 1: ((: %2: syntax error: operand expected (error token is "%2") evil  Correct result, with a bit of extra on the side. # Stax, 4 bytes :1|e  Run and debug it :1|e Full program, implicit input-evaluation :1 Count set bits |e Check if even  # R, 37 26 bytes !sum(scan()%/%2^(0:31))%%2  Try it online! An alternative to Robert S.'s answer, this eschews the built-in bit splitting but ends up less golfy and thanks to JayCe and digEmAll ends up coming in slightly golfier. Only works for positive integers less than $2^{31}-1$. • Why don't hardcode 31 instead of log2 ? Try it online! Aug 1, 2018 at 19:04 • @digEmAll Which in turn means no need to define x Aug 1, 2018 at 19:42 • @digEmAll thanks! I wasn't sure about precision issues, although I suppose that past $2^{31}-1$ we (probably) lose precision in the %/% and %% operators so it would be a moot point. Aug 1, 2018 at 19:58 • Also intToBits supports only integer values up to 2^31-1 ;) Aug 1, 2018 at 20:19 # R, 99984434 28 bytes -1 thanks to Kevin Cruijssen! -54 thanks to ngm! -10 thanks to Giuseppe! -6 thanks to JayCe! !sum(intToBits(scan())>0)%%2  Try it online! Alternatively, using the binaryLogic package (39 bytes): !sum(binaryLogic::as.binary(scan()))%%2  • I don't know R too well, but I'm pretty sure ==0 can be <1 :) Aug 1, 2018 at 15:26 • 43 bytes? – ngm Aug 1, 2018 at 16:44 • Nice! 34 bytes is possible Aug 1, 2018 at 16:58 • This works as well I think : 32 bytes But requires a bit of an explanations :) Aug 1, 2018 at 18:23 • it's easy to turn this into a full program for some more bytes Aug 1, 2018 at 19:45 # Brachylog, 4 bytes ḃo-0  Try it online! With multiple test cases (😈 is evil and 👼 is not.) Uses something I discovered recently about the - predicate: its documentation just says "the difference of elements of [input]", but what it actually does is "sum of even-indexed elements (starting from 0th) of input, minus the sum of odd-indexed elements of input". Here, ḃ converts the number into an array of binary digits, o sorts them to bring all the 1s together. Now, if there were an even number of 1s, there would be an equal number of 1s in even indices and odd indices. So the - after that would give a 0. But if there were an odd number of 1s, there would be an extra 1 sticking out, resulting in the difference being either -1 or 1. So, finally, we assert that the difference is 0, and get a true or false result according to that. With more flexible output requirements, this could be removed for a 3 byte answer, with 0 as truthy output and -1 and 1 as both falsey outputs. # x86-16, 3 bytes NASM listing:  1 parity16: 2 00000000 30E0 xor al,ah 3 00000002 C3 ret  16-bit integer function arg in AX (which is destroyed), return value in PF. The hardware calculates the parity of the result for us, in x86's Parity Flag. The caller can use jp / jnp to branch, or whatever they like. Works exactly like @cschultz's Z80 / 8080 answer; in fact 8086 was designed to make mechanical source-porting from 8080 easy. Note that PF is only set from the low byte of wider results, so test edi,edi wouldn't work for an x86-64 version. You'd have to horizontal-xor down to 16 bits, or popcnt eax, edi / and al,1 (where 0 is truthy). # INTERCAL, 9065 63 bytes DOWRITEIN:1 DO:2<-'#0$#65535'~?':1~:1'


Try it online!

Ungolfed and expanded (for what it's worth) with C style comments.

DO WRITE IN :1 //Store user input in 1
DO :2<-:1~:1 //Select just the ones. So will convert binary 10101 to 111
DO :3<-:?2 //Run the unary xor over the result. Essentially, xor with the right bitshifted
//(with wraparound) value).
DO :9<-#0$#65535 //Intermingle the 16 bit values of all 0's and all 1's, to create a //32 bit number with 1's in the odd positions. DO :4<-:9~:3 //It turns out that at this point, evil numbers will have no bits in odd //positions, and non-evil numbers will have precisely one bit in an odd //position. Therefore, the ~ will return 0 or 1 as appropriate. PLEASE READ OUT :4 //Politely output PLEASE GIVE UP //Polite and self explanatory  I had to make a few concessions to make this feasible in INTERCAL. The first is, as with all INTERCAL programs, numerical input must be written out. So if you want to input 707 you would provide SEVEN OH SEVEN. The second is that INTERCAL doesn't really have proper truthy or falsy value. Instead, it will output the Roman Numeral I (1) if the number is not evil, or a 0 (typically represented as - since Roman Numerals can't normally represent 0). If you want to flip those so that evil numbers return 1 and non-evil numbers return 0, you can change lines 4 and 5 from the ungolfed version as follows, although it does add 3 bytes. DO:9<-#65535$#0
DO:4<-#1~:9~3


# PHP, 37 36 bytes

<?=1&~substr_count(decbin($argn),1);  To run it: echo '<input>' | php -nF <filename>  Prints 1 for true, and 0 for false. -1 byte thanks to Benoit Esnard! • I think you can save one byte by removing the modulo operation: <?=1&~substr_count(decbin($argn),1);. This one also prints 0 for false. Aug 2, 2018 at 11:45
• Thanks @BenoitEsnard! That's very clever, I've updated my answer :) You learn something new every day! Aug 2, 2018 at 12:09

# C (gcc), 36 bytes

c;f(n){for(c=0;n;c++)n&=n-1;n=~c&1;}


Try it online!

Must be compiled with optimization level 0

• Doesn't compile on gcc 5.4.0: error: expected constructor, destructor, or type conversion before '(' token (arrow is pointing at the f in the function name). What compiler flag(s) do I need? Aug 1, 2018 at 21:52
• Doesn't work with -O. Aug 1, 2018 at 23:19
• "Returns 0 for truthy, 1 for falsey" Is this legal? Not trying to discredit your answer, just curious, and because it would save me a byte. Note: The word truthy in the question links to this answer. And this comment also mentions truthiness. Aug 2, 2018 at 19:09
• @nwellnhof @villapx Compiles fine on my 7.3.0 - just make sure you're not missing the -O0 compiler flag.
– user77406
Aug 2, 2018 at 21:02
• @Borka223 hmmm after months of perusing this site, I was under the impression that truthy and falsey could be anything, so long as they are consistent within your solution. However, the answer you linked certainly seems to contradict that. I went ahead and added the byte. Thanks
– vazt
Aug 2, 2018 at 21:54

# Wolfram Language (Mathematica), 24 22 bytes

2∣DigitCount[#,2,1]&

Try it online!

• 2∣ is an improvement on EvenQ. Try it online! Oct 21, 2018 at 4:31

# x86-16 machine code, 3 bytes

32 C4     XOR  AL, AH     ; PF = (AX >> 8) XOR AL


Input is AX, output is in PF; PE if True (Evil) or PO if False (Not Evil).

This is actually the exact use of the x86 Parity Flag, with the only twist being that normally it only operates on the LSB of a WORD register. However, you can get the Parity of a WORD by XOR'ing the high byte and the low byte.

Example output from a test program for PC DOS:

DANG IT, I should have looked at the other answers first... @PeterCordes submitted this in 2018...

https://codegolf.stackexchange.com/a/169903/84624

# evil, 4842403936 35 bytes

golf 1: flipping many ms to js and js to ms saved quite a bit of marking mode changes
golf 2: do..while -> repeat..until
golf 3: tbxb -> sxb - can be seen to be the same, but less intuitive
golf 4: the vzv in vtfvzv turned out to be renundant, because the accumulator already zero at that point
golf 5: aayuoy -> aluoy and tbuw -> tbaw, now outputs 0x02 for evil and 0x00 for normal
I can confirm that this language is absolutely evil. Even though it is more powerful than e.g. brainfuck, it feels worse. Inputs via char code, outputs via char code (0x02 = evil, 0x00 = normal). This would be slightly (probably by 1 byte) shorter if the output values could be merely consistent and not necessarily falsy and truthy.

Uses a trick: to count set bits, the code adds elements to the wheel, a circular list, and then calculates the list size's parity by setting the first one to 1, the second one to 2 and traversing the list 2 steps at a time until a non-zero element is found.

rvmvtfxjxutctbuvavsxbmaluoymiiptbaw


Here's an explained version (I do not expect anybody to understand the monstrosity above, but the explanation is in a spoiler so that you can try) (I was also writing the code immediately with these comments):

COMMENTS ARE UPPERCASE, CODE IS LOWERCASE

r READ INPUT AS CHAR CODE
NOW DECREASE AND CHECK PARITY, WHILE ALSO COMPUTING N/2 IN THE FIRST PENTAL CELL
v STORE TO FIRST PENTAL CELL
m BEGINNING OF OUTER LOOP

vtf IF ZERO, DONE
NOW THE ACCUMULATOR HAS THE CORRECT VALUE AND THE PENTAL CELL IS ZERO, JUST LIKE IT SHOULD BE.

x SET MARKING MODE INITIALLY
j BEGINNING OF INNER LOOP
x UNSET MARKING MODE AGAIN
u FIRST DECREMENT
IF ZERO (ODD), INCREASE BIT COUNTER AND PROCEED TO NEXT ITERATION
tc THIS LANGUAGE SEEMS COMPARABLE TO MALBOLGE. THIS ADDS A NEW CELL TO THE WHEEL, A RESIZABLE CIRCULAR LIST. I USE IT AS THE BIT COUNTER
tb GO TO NEXT ITERATION OF OUTER LOOP
ODD CASE HANDLED. EVEN CASE IS (MUCH) SIMPLER
u SECOND DECREMENT
vav INCREMENT FIRST PENTAL CELL

sxb IF ZERO, GO TO THE NEXT ITERATION OF THE OUTER LOOP; ELSE GO TO THE NEXT ITERATION OF THE INNER LOOP; EQUIVALENT TO TBXB.

m END OF OUTER LOOP

DO SORCERY TO COUNT WHEEL CELLS.
al SET FIRST WHEEL CELL TO 1 (AND RESET THE ACCUMULATOR BACK TO 0 BY SWAPPING)
uoy SET SECOND CELL TO -1

NOW IN A LOOP CHECK WHETHER 1 OR 2 GOES FIRST AND OUTPUT THE CORRESPONDING NUMBER

m BEGINNING OF THE LOOP
ii GO RIGHT TWICE
tb IF STILL ZERO, GO BACK
NOW THE NON-ZERO ELEMENT WAS FOUND
a INCREMENT SO THAT VALUES ARE ACTUALLY FALSY AND TRUTHY. IF THAT REQUIREMENT WASN'T THERE, THE CODE COULD BE REDUCED SLIGHTLY (AT LEAST BY REMOVING THIS BYTE)
w PRINT


Now, the most evil part. This code does not work with the normal interpreter, because it has a bug. The bug is that the command to add a cell to the wheel quite literally doesn't add a cell to the wheel (to be specific, it's missing wheelSize++;). I assume that the bug is obvious enough for me to avoid accusations of adding new built-ins to the language.

You can Try it online! using my fixed interpreter.

• Bonus: Is you code as a base64 number evil?
– user96495
Aug 24, 2020 at 2:22
• @petStorm seems to be evil both in base64 and base36 :) Aug 24, 2020 at 2:58

# C++ (gcc) (-O0),  36  31 bytes

int f(int i){i=!i||i%2-f(i/2);}


Try it online!

# C++ (clang), 35 bytes

int f(int i){return!i||i%2-f(i/2);}


Try it online!

Here is my first attempt at code golfing, hope I didn't break any rule I might have missed.

Edit:
- Saved 5 bytes thanks to @Jonathan Frech : replaced != by - and return by i= (the last replacement does not seem to work with clang though)
- Since there seems to be a debate whether I should use gcc -O0 abuse, I thought I could just give both versions

• Welcome to PPCG! You may be able to save a byte by golfing != to - and another four by golfing return to i=. Aug 2, 2018 at 12:17
• @JonathanFrech It's been a long time since I did C++, does it implicitly return the last assigned expression in a function if there's no return statement? I'm guessing it's a gcc thing? Aug 2, 2018 at 16:26
• It is a gcc specific undefined behaviour abuse on optimization level O0. Aug 2, 2018 at 17:45
• By switching to K&R C, you can get it down to 23 bytes (very impressive!) Try it online! Aug 2, 2018 at 22:01
• @PeterCordes For one I do not insist on this compiler-specific quirk, but I merely suggested it as it does save bytes. Our current policy allows every such quirk in any language implementation; I do not think that is "stupid". Furthermore, we strive to golf our submissions as far as possible. If you do not like this method, you can always write in a more specific flavour of C, like C clang or C using O1. Aug 3, 2018 at 12:42

# Attache, 13 12 bytes

Even@Sum@Bin


Try it online!

(Old 13 bytes: Even@1&~@Bin)

This is a composition of three functions:

1. Bin
2. Sum
3. Even

This checks that the Sum of the Binary expansion of the input is Even.

• :| i have no words Aug 6, 2018 at 6:51
• @ASCII-only quite succinct, eh? c: Aug 6, 2018 at 6:55

# dc, 18 16 bytes

[2~rd1<M+]dsMx2%


Returns (to the stack) 0 for evil and 1 for not evil

Try it online!

Fairly straightforward - recursively applies the combined quotient/remainder operator ~ to the new quotient and adds all the remainders together, then mods by 2 (after spending two bytes to flip to a standard truthy/falsy).

Edited to reflect consensus that 0 for truthy and 1 for falsy is okay, especially in a language that has no sort of if(boolean) construct.

# APL (Dyalog Unicode), 10 bytesSBCS

Anonymous tacit function. Can take any array of integers as argument.

≠⌿1⍪2∘⊥⍣¯1


Try it online!

2∘⊥⍣¯1 convert to binary, using as many digits as needed by the largest number, separate digits along primary axis

1⍪ prepend ones along the primary axis

≠⌿ XOR reduction along the primary axis

# Python 2, 29 bytes

lambda n:~bin(n).count('1')&1


Try it online!

Returns 1 if True, else 0.

Converts the number to a binary string like '0b11', counts the number of 1s, gets the complement of result, and returns the last bit of the complement (thanks, https://codegolf.stackexchange.com/users/53560/cdlane!) (1 if the original number was even, 0 if it was odd).

• No fewer bytes but lambda n:~bin(n).count('1')&1 replaces the modular division with something potentially less expensive. Aug 2, 2018 at 6:22
• You can do lambda x:~x.bit_count()%2 which is shorter May 12 at 22:17

# Wolfram Language (Mathematica), 14 bytes

ThueMorse@#<1&


Try it online!

The Nth element of the Thue-Morse sequence is 1 if the number of binary digits in N is odd, and 0 otherwise.

Since the previous J solution by Adam is invalid for numbers having odd number of binary digits, here is a corrected one:

# J, 8 bytes

1-~:/&#:


Try it online!

Anonymous tacit verb.

### How it works

1-~:/&#:    Right argument: the number to test.
#:    Convert to binary digits
~:/&      Reduce by not-equal (same as XOR for zero-one values)
1-          Invert the result


Alternatively, J has a built-in XOR that computes bitwise XOR over the input.

# J, 8 bytes

1-XOR&#:


Try it online!

# C# (.NET Core), 34 bytes

bool f(int i)=>i<1||i%2<1==f(i/2);


Try it online!

There were already a few C# solutions, but this is the first recursive one.

In the case case when no more 1's are present, the function is terminated with a positive result. Otherwise the lowest bit is tested. If it is set, then the count of the rest of the bits must be odd. If it is unset, then the count of the rest of the bits must be even. We are able to determine whether the count of the remaining bits is even/odd by making a recursive call to half the input.

# SML, 32 Bytes

fun%0=1| %n=(n+ %(n div 2))mod 2


Explaination:

• % is function name
• takes in input in repl and returns 1 if evil, 0 otherwise
• n is input, returns (n + %(n//2)) % 2

Made by 2 bored Carnegie Mellon Students

• Welcome to PPCG, and good first answer! Feb 6, 2019 at 20:00

# Ruby, 32292827 21 bytes

->n{("%b"%n).sum%2<1}


Where we use the fact that sum sums each character and given 1 is an odd number, and because we eventually do modulus 2, that makes it equivalent to count(?1):

->n{("%b"%n).count(?1)%2<1}


Where <1 is a shorter substitute for even?:

->n{n.to_s(2).count(?1).even?}


Where n parameter should be an integer.

• %2==0 saves 1 byte. Aug 2, 2018 at 14:02
• @iamnotmaynard, thank you, thank you! I couldn't accept that python solution would be shorter :) wow, now I see it got 27 :/ Aug 2, 2018 at 16:22
• Instead of %2==0 can't you do something like %2<1 to save a byte? Aug 2, 2018 at 16:28
• @auhmaan Oh yeah, even better. Aug 2, 2018 at 16:31
• ("%b"%n).count(?1)%2 is the same as ("%b"%n).sum%2
– G B
Feb 12, 2020 at 8:20

# Java (JDK 10), 20 bytes

-6 bytes thanks to Roberto Graham

n->n.bitCount(n)%2<1


Try it online!

• 20 bytes Try it online! Aug 6, 2018 at 17:11
• @RobertoGraham Thanks, forgot you can call static methods on a variable.
– Okx
Aug 6, 2018 at 17:13

# Regex (ECMAScript), 37 33 bytes

-4 bytes thanks to Neil's idea of subtracting the least-significant two bits instead of the most-significant two bits

^(((?=(((x*)(?=\5$))*))\3x){2})*$


Try it online!

Takes its input in unary, as a string of x characters whose length represents the number.

^
(
# Subtract the two least-significant "1" bits as
# they would be in tail's binary representation.
(
# Divide tail evenly by 2 as many times as we can, atomically
(?=
(((x*)(?=\5$))*) )\3 x # Subtract a 1 bit ){2} )* # Loop as many times as possible...$                        # and only match if the final result is 0.


## Regex (Perl / Java / PCRE / Python / Ruby), 26 bytes

^((((x*)(?=\4$))*+x){2})*$


Try it online! - Perl
Try it online! - Java
Try it online! - PCRE
Try it online! - Python import regex
Try it online! - Ruby

^
(
# Subtract the two least-significant "1" bits as
# they would be in tail's binary representation.
(
# Divide tail evenly by 2 as many times as we can, atomically
((x*)(?=\4$))*+ x # Subtract a 1 bit ){2} )* # Loop as many times as possible...$                        # and only match if the final result is 0.


## Regex (.NET), 29 bytes

^(((?>((x*)(?=\4$))*)x){2})*$


Try it online!

• ^((((.*)(?=\4$))*.(.*)(?=\5$)){2})*\$` is only 36 bytes.
– Neil
Feb 5, 2019 at 10:34