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). – Kevin Cruijssen Aug 1 '18 at 15:25
• Possible duplicate of Count the number of ones in an unsigned 16-bit integer – Beta Decay Aug 1 '18 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. – Amphibological Aug 1 '18 at 20:29
• I believe that 666 => False should be a test case. – user2390246 Aug 2 '18 at 10:38
• Yes, 666 is not evil, but 616 is. More evidence corroborating Papyrus 115! – aschepler Aug 7 '18 at 11:41

Bash + GNU utilities, 33

dc -e2o?p|tr -d 0|wc -c|dc -e?2%p


Try it online!

Reads input from STDIN. Outputs 1 for True and 0 for False.

• dc converts input to a binary string
• tr removes zeros
• wc counts remaining ones (and trailing newline, which corrects sense of logic
• dc calculates count mod 2 and outputs the answer

Python 2, 28 27 bytes

f=lambda n:n<1or n&1^f(n/2)


Try it online!

Returns a truthy value if exactly one of the ones-bit is a 1 and the result of calling this function on n/2 is truthy is true (or n==0). It works because n/2 is equivalent to a right bitshift with floor division (so Python 2 only).

Alternate version, also 28 27 bytes

g=lambda n:n<1or g(n&n-1)^1


Try it online!

Based on the K&R method of counting set bits referenced by vazt.

Both of these could be two bytes shorter if the output allowed falsey to mean evil.

Edit: Thanks to Amphibological for saving a byte!

• You can remove the spaces between the 1 and the or to save +1 byte. Nice solution! – Amphibological Aug 2 '18 at 0:22
• Man, I thought I tried that. Good catch! – Jack Brounstein Aug 2 '18 at 2:05

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

J, 9 bytes

Anonymous tacit function. Can take any integer array as argument.

1-2|1#.#:


Try it online!

1- one minus (i.e. logical negation of)

2| the mod-2 of

1#. the sum (lit. the base-1 evaluation) of

#: the binary representation

• Nice one! the boring approach is 9 bytes: 2|1+1#.#: – Conor O'Brien Aug 1 '18 at 21:21
• This only seems to work because 777 in the input makes every number be represented in 10 bits. Replace it with e.g. 480 and the output flips. – FrownyFrog Aug 1 '18 at 22:45
• @ConorO'Brien Boring trumps incorrect. – Adám Aug 2 '18 at 7:43
• @FrownyFrog Fixed. – Adám Aug 2 '18 at 7:43

C#, 65 bytes

So I'm terrible at codegolf, but here's my hacky string + LINQ solution:

n=>{return Convert.ToString(n,2).Where(c=>c=='1').Count()%2==0;};


Try it online!

• A few tips: .Where(c=>c=='1') you can save 1 byte by comparing if c is bigger than '0', and you can save another byte by changing '0' to the decimal representation 48. One more byte can be saved on .Count()%2==0 by comparing if the result is less than 1, resulting in this solution: n=>{return Convert.ToString(n,2).Where(c=>c>48).Count()%2<1;}; – auhmaan Aug 2 '18 at 16:13
• Also, you can save more 8 bytes by moving the predicate from Where to Count and removing the Where completely. Your solution would end up like this n=>{return Convert.ToString(n,2).Count(c=>c>48)%2<1;}; for a total of 54 bytes. – auhmaan Aug 2 '18 at 16:14

C# (.NET Core), 5048 45 bytes

-3 bytes thanks to Charlie

n=>{int i=0;for(;n>0;n/=2)i^=n%2;return i<1;}


Try it online!

• 47 bytes using a for instead of a while. And welcome to PPCG! – Charlie Aug 2 '18 at 12:59
• Sorry, 45 bytes using your XOR solution. – Charlie Aug 2 '18 at 13:05
• @Charlie: Edited, thanks for the tip – F.Carette Aug 2 '18 at 14:22

Excel, 434139 41 bytes

-2 bytes thanks to Keeta
-2 bytes thanks to Sophia Lechner
+2 bytes thanks to sundar

Original:

=MOD(LEN(SUBSTITUTE(DEC2BIN(A1),0,"")),2)=0


Shortest version:

=MOD(LEN(SUBSTITUTE(DEC2BIN(A1),0,)),2)=0

• Since "" is the default third argument for SUBSTITUTE, you can save two bytes with =MOD(LEN(SUBSTITUTE(DEC2BIN(A1),0,)),2)=0 – Sophia Lechner Aug 1 '18 at 19:06
• If you change your "truthy/falsey" to be 1 and 0 instead of TRUE and FALSE, you can omit the last "=0" – Keeta - reinstate Monica Aug 1 '18 at 19:36
• (regarding clarifying last comment) - true would be 0 and false would be 1. Then... you could further golf by omitting the 0 in the SUBSTITUTE statement and Excel assumes a 0 - but then you have to leave the quotes in. Better to take out the quotes instead – Keeta - reinstate Monica Aug 1 '18 at 19:48
• @SophiaLechner, what version of Excel are you using? This doesn't seem to be the case in Excel 2013 – Eric Canam Aug 1 '18 at 19:50
• Note that question links to a meta answer which gives a specific definition of truthy/falsey: you should be able to use the output in a conditional, for eg., =IF() in this case, and have it work like TRUE or FALSE. Many other questions have more flexible output requirements, so 0 for true and 1 for false would be fine there, but here I think you'll have to stick to the 41 byte version. – sundar - Reinstate Monica Aug 2 '18 at 17:29

C (gcc), 29 bytes

f(a){a=!__builtin_parity(a);}

Uses a GCC builtin, and exploits how GCC handles return values, only works at -O0 optimization level (the default).

Try it online!

JavaScript (Babel Node), 39 bytes

-1 Bytes thnks to @OMᗺ =D

_=>eval('for(z=0;_;_>>=1)z+=_&1;z%2<1')


Try it online!

MATLAB / Octave, 2827 25 bytes

Using the de2bi function from the comm. systems MATLAB toolbox, you can achieve 25 bytes

@(n)~mod(sum(de2bi(n)),2)


Here is the 27 byte version which works without toolboxes (so works in Octave):

@(n)~mod(sum(dec2bin(n)),2)


The dec2bin conversion outputs a character array, so counting the occurence of the character '1' mod 2 gives the opposite of an evil number, negating that with ~ gives the answer.

Edited to include Sundar's comments (made it a valid anonymous function and saved by leveraging ASCII values instead of comparing to '1').

• de2bi(n) can replace dec2bin(n)=='1' if toolboxes are allowed. – Orhym Aug 2 '18 at 1:19
• I think submissions have to be either full programs or functions, so you'll have to add a @(n) at the beginning to make this an anonymous function. You can save 2 bytes by replacing =='1' with -48 though. – sundar - Reinstate Monica Aug 2 '18 at 14:35
• I believe @(n)~mod(sum(dec2bin(n)),2) would also work, for total 27 bytes. (Works because '1' is ASCII 49, so the result of the sum will be even only if there are an even number of '1' characters in the dec2bin result.) – sundar - Reinstate Monica Aug 2 '18 at 14:41
• @sundar Thanks, included – Wolfie Aug 2 '18 at 14:59
• @Ander Cheers, orhym had suggested this too but don't know why I didn't add it in. – Wolfie Aug 3 '18 at 10:27

Lua 5.3.4, 63 62 bytes

-1 bytes thanks to Jo King

function e(n)o=0while n>0 do o=o+n n=n//2 end return o%2<1 end


function e(n)
o=0
while n>0 do
o=o+n
n=n//2
end
return o%2<1
end


n is the input and integer divided by 2 until it is equal to 0. o is incremented by n, and its parity is what determines the output. This function returns true if evil or false if odious (not evil).

• Good point! I'll edit my answer! – GalladeGuy Aug 3 '18 at 16:51

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!

CJam, 161411 10 bytes

Can't believe there's no CJam/GolfScript answer yet.

qi2b1e=1&!


Try it out! (Online)

Explanation

qi                     Reads input as an integer
2b                   Converts it to an array of its digits in base 2 (binary)
1e=                Checks the number of occurrences of 1 in that array
1&              The rightmost bit of the number of 1s (a test for evenness)
!             Unfortunately we need to return 1 for evenness and not 0 (and vice versa)
Implicit output 1 for true and 0 for false


This answer isn't very good in comparison to other answers here, but I might as well post and see if some CJam people can help golf this answer further.

Changes:

Helen cut off 2 bytes!

Old: qi2b1e=2%0={1}0?
New: qi2b1e=2%0=X0?

By replacing the block ({1}) with X (whose value is always initialised to 1) we can cut out 2 characters and don't have to add in any whitespace.
The If-Else still works without the block, funnily enough.

Helen cut off 3 bytes!

Old: qi2b1e=2%0=X0?
New: qi2b1e=2%0=

We don't need to manually push 1 and 0 to the stack depending on the result of the comparison since 1/0 are automatically pushed for true/false respectively.

Helen cut off 1 byte!

Old: qi2b1e=2%0=
New: qi2b1e=1&!

By keeping the rightmost bit of the number, we can test for evenness without having to use modulo.

Alchemist, 117 105 99 93 bytes

_->In_a+s
a+0z->z
a+z+0c->b
z+0a+0c+f->
z+0a+0c+0f->f
b+0a+0z->c
c+0b->a
0a+0b+0c+0z+s->Out_f


Try it online!

Trying out BMO's new language! Outputs 0 if the number is evil and 1 otherwise. It took me quite a while to figure out how to check if there is only one of an atom left.

Explanation:

Input
_->In_a+s     Convert the initial _ atom to input copies of atom a
And an s atom as a flag
Division
a+0z->z       Always have one z atom by converting an a atom
a+z+0c->b     Convert an a atom and a z atom to a b atom
This divides the a atoms by 2 into b atoms
With a z atom as the parity
z+0a+0c+0f->f Convert the z atom to an f atom if there aren't any f atoms
z+0a+0c+f->   If there is an f atom, remove both

Reset to calculate the next binary digit
b+0a+0z->c    Convert all b atoms to c atoms
c+0b->a       Convert all c atoms to a atoms

Output
0a+0b+0c+0z+s->Out_f  If there are no relevant atoms left
Output the number of f atoms

• wow, nice. also, close :( – ASCII-only Jan 30 '19 at 5:01
• also -1 nondeterministic :P – ASCII-only Jan 30 '19 at 5:03
• Also, haha, we came up with the same solution of checking for 1 – ASCII-only Jan 30 '19 at 5:04
• :D tie, if it works. as an added bonus, it's deterministic – ASCII-only Jan 30 '19 at 5:10
• well. if i invert output then 103 :P, and 99 without determinism – ASCII-only Jan 30 '19 at 5:23

05AB1E, 4 bytes

b1¢È


Try it online!

Converts to binary b, counts occurrences of 1 1¢, and checks if it's even È.

• I did something similar but to get counts of 1 I used S to make it a list and O to sum the list: bSOÈ – Brzyrt Feb 19 at 23:01

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.

Jelly, 4 bytes

BS2ḍ


Try it online!

Chip, 22 bytes

 ABCDEFGHe
a{{{{{{{{*f


Try it online!

Chip works in bytes, so each byte of input here is treated independently (which makes for easy test suites). The first byte is ASCII 7 (decimal 55), then 96 -> 99 and 64 -> 67.

This simply XOR's all the input bits, A-H, together (with an extra 1 to invert the result), and sets the low output bit, a, to the outcome. Output bits e and f are also set, making the program output be ASCII 0 for not-evil, and ASCII 1 for evil.

The right-to-left XOR's ({) can be replaced by right-to-left half adders (@) for the same result.

• Interesting language. It looks like the input is treated as 7-bit ASCII, so you can probably save 2 bytes by removing H and its corresponding {. – sundar - Reinstate Monica Aug 2 '18 at 16:16
• @sundar Thanks! Input is easily given as ASCII, but it actually just sees raw bytes. Any control characters, or values above 0x7f are had to express in TIO, but they do work just fine. For example, the unicode smile face is treated as the three independent bytes. – Phlarx Aug 2 '18 at 16:35
• Ah, it looks like the input characters (at least on TIO) are treated as their UTF-8 encoded bytes. Then I guess the non-terminal bytes can have their high bit set. Just curious, since you said "hard to express in TIO", is there a way to input values above 0x7f by themselves on a local interpreter? On TIO it seems possible only as part of a multibyte character (for eg., to enter 0xe4, I have to input 䀀 (UTF-8 bytes 0xe4, 0x80, 0x80) and ignore the last two outputs). – sundar - Reinstate Monica Aug 2 '18 at 17:08
• The input scheme is quite beyond the point of the language, so sorry if this seems like bikeshedding, but it seems like an extended ASCII code like ISO-8859-1 (/Windows 1252) would make more sense for input for this language, making it easier to input byte values and allowing all byte values in input (for eg. I think the current method can't take 255 as input, since bytes with values 245 - 255 are not valid UTF-8 bytes in any character). – sundar - Reinstate Monica Aug 2 '18 at 17:16
• @sundar No worries! The interpreter just uses a binary input stream, so encoding isn't even taken into account. On a command line, for example, I usually do something like printf '\xe4' | ./chip [...], though input direct from a file would work too. ASCII, in the case of this example, is purely an external consideration, a way to provide a specific set of bits in a convenient (if incomplete) way. – Phlarx Aug 2 '18 at 18:11

Pyth, 6

!xFjQ2


Explanation

   jQ2 # Convert input to base 2 list
xF    # reduce on XOR
!      # logical negation


Brachylog, 5 bytes

ḃ+%₂0


Try it online!

Explanation

ḃ       Take the binary representation of the input
+      Sum the digits
%₂0   This sum modulo 2 is 0


Pari/GP, 21 bytes

n->1-sumdigits(n,2)%2


Try it online!

• +1. Beats the faster n->1-hammingweight(n)%2. – Charles Aug 2 '18 at 15:05

f n=even.sum$mapM(pure[0,1])[1..n]!!n  Try it online! Bash, 976442 39 Bytes Thanks ilkkachu (($(bc<<<obase=2\;$1|tr -d 0|wc -c)%2))  Try it online! • Welcome to code-golf! There is quite a lot you can do here to shorten this - dc expressions are generally shorter than bc - returning True/False in a shell return code is OK - no need to do && echo false || echo true. Here is my shell answer. Some good tips here – Digital Trauma Aug 2 '18 at 0:16 • @DigitalTrauma: Thanks. I shortened it up some, still not as short as yours though. – jesse_b Aug 2 '18 at 14:00 • Doesn't that give an inverted return code? (Considering the common shell custom that zero is truthy) You could save one character by escaping just the semicolon, and a couple by replacing the variable with wc -c: (($(bc<<<obase=2\;$1|tr -d 0|wc -c)%2)) (That also changes the return value so it returns 0 for even number of ones). – ilkkachu Aug 2 '18 at 19:34 Common Lisp, 30 bytes (lambda(x)(evenp(logcount x)))  Try it online! Perl 5, 33 bytes sub e{pop=~//;$'?$'%2!=e($'/2):1}


Try it online!

Different approach, one byte longer:

sub e{(grep$_[0]&2**$_,0..31)%2^1}


Befunge-93, 23 bytes

&#2:_v#:/
v#:\+<_
_2%.@


Try it online!

Outputs 1 for non-evil, 0 for evil numbers. Calculates the parity of the sum of n divided by 2 repeatedly.

EXCEL, 106 bytes

applied Sir Taosique's answer to handle larger numbers.

=ISEVEN(LEN(SUBSTITUTE(DEC2BIN(MOD(QUOTIENT(A1,256^1),256),8)&DEC2BIN(MOD(QUOTIENT(A1,256^0),256),8),0,)))


perl -E, 39 bytes

say!((unpack"b*",pack I,pop)=~y/1/1/%2)


Rust, 24 bytes

|x:u64|!x.count_ones()%2


Try it online!