43
\$\begingroup\$

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
    

The Leaderboard

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

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# 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 ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 81420; // This should be the user ID of the challenge author.

/* App */

var answers = [],
  answers_hash, answer_ids, answer_page = 1,
  more_answers = true,
  comment_page;

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

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function(data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function(data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

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

var OVERRIDE_REG = /^Override\s*header:\s*/i;

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

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      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],
        link: a.share_link,
      });
    //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;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
      .replace("{{NAME}}", a.user)
      .replace("{{LANGUAGE}}", a.language)
      .replace("{{SIZE}}", a.size)
      .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    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,
      link: a.link
    };
  });

  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)
      .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

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

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

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

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr>
        <td>Language</td>
        <td>User</td>
        <td>Score</td>
      </tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr>
        <td></td>
        <td>Author</td>
        <td>Language</td>
        <td>Size</td>
      </tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr>
      <td>{{PLACE}}</td>
      <td>{{NAME}}</td>
      <td>{{LANGUAGE}}</td>
      <td>{{SIZE}}</td>
      <td><a href="{{LINK}}">Link</a></td>
    </tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr>
      <td>{{LANGUAGE}}</td>
      <td>{{NAME}}</td>
      <td>{{SIZE}}</td>
      <td><a href="{{LINK}}">Link</a></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.

\$\endgroup\$
  • 2
    \$\begingroup\$ Related (XOR-ing every binary digit is the same as taking the sum modulo-2). \$\endgroup\$ – Kevin Cruijssen Aug 1 '18 at 15:25
  • 4
    \$\begingroup\$ Possible duplicate of Count the number of ones in an unsigned 16-bit integer \$\endgroup\$ – Beta Decay Aug 1 '18 at 17:11
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ – Amphibological Aug 1 '18 at 20:29
  • 15
    \$\begingroup\$ I believe that 666 => False should be a test case. \$\endgroup\$ – user2390246 Aug 2 '18 at 10:38
  • 2
    \$\begingroup\$ Yes, 666 is not evil, but 616 is. More evidence corroborating Papyrus 115! \$\endgroup\$ – aschepler Aug 7 '18 at 11:41

100 Answers 100

2
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

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!

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

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

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Nice one! the boring approach is 9 bytes: 2|1+1#.#: \$\endgroup\$ – Conor O'Brien Aug 1 '18 at 21:21
  • \$\begingroup\$ 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. \$\endgroup\$ – FrownyFrog Aug 1 '18 at 22:45
  • \$\begingroup\$ @ConorO'Brien Boring trumps incorrect. \$\endgroup\$ – Adám Aug 2 '18 at 7:43
  • \$\begingroup\$ @FrownyFrog Fixed. \$\endgroup\$ – Adám Aug 2 '18 at 7:43
2
\$\begingroup\$

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!

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ 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;}; \$\endgroup\$ – auhmaan Aug 2 '18 at 16:13
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – auhmaan Aug 2 '18 at 16:14
2
\$\begingroup\$

C# (.NET Core), 50 48 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!

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

Excel, 43 41 39 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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Since "" is the default third argument for SUBSTITUTE, you can save two bytes with =MOD(LEN(SUBSTITUTE(DEC2BIN(A1),0,)),2)=0 \$\endgroup\$ – Sophia Lechner Aug 1 '18 at 19:06
  • \$\begingroup\$ If you change your "truthy/falsey" to be 1 and 0 instead of TRUE and FALSE, you can omit the last "=0" \$\endgroup\$ – Keeta - reinstate Monica Aug 1 '18 at 19:36
  • \$\begingroup\$ (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 \$\endgroup\$ – Keeta - reinstate Monica Aug 1 '18 at 19:48
  • \$\begingroup\$ @SophiaLechner, what version of Excel are you using? This doesn't seem to be the case in Excel 2013 \$\endgroup\$ – Eric Canam Aug 1 '18 at 19:50
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – sundar - Reinstate Monica Aug 2 '18 at 17:29
2
\$\begingroup\$

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!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

JavaScript (Babel Node), 39 bytes

-1 Bytes thnks to @OMᗺ =D

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

Try it online!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

MATLAB / Octave, 28 27 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').

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ de2bi(n) can replace dec2bin(n)=='1' if toolboxes are allowed. \$\endgroup\$ – Orhym Aug 2 '18 at 1:19
  • \$\begingroup\$ 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. \$\endgroup\$ – sundar - Reinstate Monica Aug 2 '18 at 14:35
  • 1
    \$\begingroup\$ 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.) \$\endgroup\$ – sundar - Reinstate Monica Aug 2 '18 at 14:41
  • \$\begingroup\$ @sundar Thanks, included \$\endgroup\$ – Wolfie Aug 2 '18 at 14:59
  • 1
    \$\begingroup\$ @Ander Cheers, orhym had suggested this too but don't know why I didn't add it in. \$\endgroup\$ – Wolfie Aug 3 '18 at 10:27
2
\$\begingroup\$

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

More readable version:

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).

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Good point! I'll edit my answer! \$\endgroup\$ – GalladeGuy Aug 3 '18 at 16:51
2
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

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!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

CJam, 16 14 11 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.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

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

05AB1E, 4 bytes

b1¢È

Try it online!

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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È \$\endgroup\$ – Brzyrt Feb 19 at 23:01
2
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Jelly, 4 bytes

BS2ḍ

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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 {. \$\endgroup\$ – sundar - Reinstate Monica Aug 2 '18 at 16:16
  • \$\begingroup\$ @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. \$\endgroup\$ – Phlarx Aug 2 '18 at 16:35
  • \$\begingroup\$ 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). \$\endgroup\$ – sundar - Reinstate Monica Aug 2 '18 at 17:08
  • \$\begingroup\$ 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). \$\endgroup\$ – sundar - Reinstate Monica Aug 2 '18 at 17:16
  • \$\begingroup\$ @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. \$\endgroup\$ – Phlarx Aug 2 '18 at 18:11
1
\$\begingroup\$

Pyth, 6

!xFjQ2

Explanation

   jQ2 # Convert input to base 2 list
 xF    # reduce on XOR
!      # logical negation
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Pari/GP, 21 bytes

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

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ +1. Beats the faster n->1-hammingweight(n)%2. \$\endgroup\$ – Charles Aug 2 '18 at 15:05
1
\$\begingroup\$

Haskell, 37 bytes

f n=even.sum$mapM(pure[0,1])[1..n]!!n

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Bash, 97 64 42 39 Bytes

Thanks ilkkachu

(($(bc<<<obase=2\;$1|tr -d 0|wc -c)%2))

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – Digital Trauma Aug 2 '18 at 0:16
  • \$\begingroup\$ @DigitalTrauma: Thanks. I shortened it up some, still not as short as yours though. \$\endgroup\$ – jesse_b Aug 2 '18 at 14:00
  • \$\begingroup\$ 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). \$\endgroup\$ – ilkkachu Aug 2 '18 at 19:34
1
\$\begingroup\$

Common Lisp, 30 bytes

(lambda(x)(evenp(logcount x)))

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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,)))
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

perl -E, 39 bytes

say!((unpack"b*",pack I,pop)=~y/1/1/%2)
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Rust, 24 bytes

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

Try it online!

| improve this answer | |
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.