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

136 Answers 136

3
\$\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.

\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to PPCG, and good first answer! \$\endgroup\$
    – mbomb007
    Commented Feb 6, 2019 at 20:00
3
\$\begingroup\$

Java (JDK 10), 20 bytes

-6 bytes thanks to Roberto Graham

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

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 20 bytes Try it online! \$\endgroup\$ Commented Aug 6, 2018 at 17:11
  • 1
    \$\begingroup\$ @RobertoGraham Thanks, forgot you can call static methods on a variable. \$\endgroup\$
    – Okx
    Commented Aug 6, 2018 at 17:13
3
\$\begingroup\$

Rust, 24 bytes

|x:u8|x.count_ones()&1<1

Note that this only works for 8-bit numbers. The following works for 64-bit (but is an extra character):

|x:u64|x.count_ones()&1<1

Testing code:

fn main() {
    let f = |x:u64|x.count_ones()&1<1;

    const TESTS: [(u64, bool); 6] = [
        (3, true),
        (11, false),
        (777, true),
        (43, true),
        (55, false),
        (666, false)
    ];

    for (x, b) in TESTS {
        assert_eq!(f(x), b);
    }
}
\$\endgroup\$
3
+100
\$\begingroup\$

Vyxal, 4 bytes

b1O₂

Try it Online!

\$\endgroup\$
2
\$\begingroup\$

Forth (gforth), 53 bytes

: f 1 swap begin 2 /mod -rot xor swap ?dup 0= until ;

Try it online!

Explanation

Takes the xor-sum of the digits of the binary form of the number. (repeatedly divides by 2 and xors the remainder with the "sum" value)

Code Explanation

: f              \ begin a new word definition
  1 swap         \ place 1 on the stack below the input (n)
  begin          \ start an indefinite loop
    2 /mod       \ get the quotient and remainder of dividing n by 2
    -rot         \ move the sum and remainder to the top of the stack
    xor          \ xor the sum and remainder
    swap         \ move the quotient back to the top of the stack
    ?dup         \ duplicate if > 0
    0=           \ get "boolean" indicating if quotient is 0
  until          \ end the loop if it is, otherwise go back to the beginning
;                \ end the word definition
\$\endgroup\$
2
\$\begingroup\$

Java 8, 40 36 bytes

n->n.toString(n,2).chars().sum()%2<1

-4 bytes thanks to @Okx for something I shouldn't have forgotten myself..

Try it online.

Explanation:

n->                // Method with Integer parameter and boolean return-type
  n.toString(n,2)  //  Convert the integer to a binary String
   .chars()        //  Convert that to an IntStream of character-encodings
   .sum()          //  Sum everything together
    %2<1           //  And check if it's even

Note that the character encoding for 0 and 1 are 48 and 49, but summing them and taking modulo-2 still holds the correct results because 48%2 = 0 and 49%2 = 1.

\$\endgroup\$
4
  • 2
    \$\begingroup\$ n.toString(n,2) saves 4 bytes. \$\endgroup\$
    – Okx
    Commented Aug 1, 2018 at 15:55
  • \$\begingroup\$ @Okx Not sure how I forgot about that one, lol.. Thanks! ;) \$\endgroup\$ Commented Aug 1, 2018 at 17:39
  • \$\begingroup\$ If you're allowed to use 1 and 0 instead of true and false (not sure for Java), you can change to: ~n.toString(n,2).chars().sum()%2 to save one byte. \$\endgroup\$ Commented Aug 1, 2018 at 19:20
  • 1
    \$\begingroup\$ @MarDev Unfortunately 0 and 1 aren't truthy/falsey in Java, only booleans/Booleans are. If a challenge would state two distinct outputs are allowed the <1 could have been removed to save 2 bytes indeed. :) \$\endgroup\$ Commented Aug 1, 2018 at 21:02
2
\$\begingroup\$

Retina 0.8.2, 28 bytes

.+
$*
+`(1+)\1
$+0
0

11

^$

Try it online! Link includes test cases. Explanation:

.+
$*

Convert to unary.

+`(1+)\1
$+0

Partial binary conversion (leaves extra zeroes).

0

Delete all the zeros.

11

Modulo the ones by two.

^$

Test whether the result is zero.

\$\endgroup\$
2
\$\begingroup\$

x86 Assembly, 12 11 bytes

F3 0F B8 44 24 04  popcnt      eax,dword ptr [esp+4] ; Load EAX with the number of ones in arg
F7 D0              not         eax ; One's complement negation of EAX
24 01              and         al,1 ; Isolate bottom bit of EAX
C3                 ret             

-1 byte thanks to @ceilingcat's suggestion

\$\endgroup\$
7
  • \$\begingroup\$ @ceilingcat Good catch! \$\endgroup\$ Commented Aug 1, 2018 at 20:01
  • 1
    \$\begingroup\$ Suggest inc eax instead of not eax. Also may want to mention that this requires a processor with support for the popcnt instruction. \$\endgroup\$
    – ceilingcat
    Commented Aug 1, 2018 at 20:15
  • 1
    \$\begingroup\$ also you do not have to take arg from stack. see allowed calling conventions codegolf.stackexchange.com/a/161497/17360 (Peter Cordes's more in-depth answer codegolf.stackexchange.com/a/165020/17360) \$\endgroup\$
    – qwr
    Commented Aug 1, 2018 at 20:43
  • 1
    \$\begingroup\$ Note that you may return a boolean in FLAGS stackoverflow.com/a/48382679/3163618 \$\endgroup\$
    – qwr
    Commented Aug 1, 2018 at 20:47
  • \$\begingroup\$ Shouldn't 666 be a test case? \$\endgroup\$ Commented Aug 1, 2018 at 21:08
2
\$\begingroup\$

Pyth, 6

!xFjQ2

Explanation

   jQ2 # Convert input to base 2 list
 xF    # reduce on XOR
!      # logical negation
\$\endgroup\$
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
\$\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!

\$\endgroup\$
1
  • \$\begingroup\$ You can remove the spaces between the 1 and the or to save +1 byte. Nice solution! \$\endgroup\$ Commented Aug 2, 2018 at 0:22
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

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

\$\endgroup\$
2
  • 2
    \$\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
    Commented Aug 2, 2018 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
    Commented Aug 2, 2018 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!

\$\endgroup\$
3
  • \$\begingroup\$ 47 bytes using a for instead of a while. And welcome to PPCG! \$\endgroup\$
    – Charlie
    Commented Aug 2, 2018 at 12:59
  • \$\begingroup\$ Sorry, 45 bytes using your XOR solution. \$\endgroup\$
    – Charlie
    Commented Aug 2, 2018 at 13:05
  • \$\begingroup\$ @Charlie: Edited, thanks for the tip \$\endgroup\$
    – F.Carette
    Commented Aug 2, 2018 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
\$\endgroup\$
6
  • \$\begingroup\$ Since "" is the default third argument for SUBSTITUTE, you can save two bytes with =MOD(LEN(SUBSTITUTE(DEC2BIN(A1),0,)),2)=0 \$\endgroup\$ Commented Aug 1, 2018 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\$ Commented Aug 1, 2018 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\$ Commented Aug 1, 2018 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
    Commented Aug 1, 2018 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 R
    Commented Aug 2, 2018 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!

\$\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!

\$\endgroup\$
0
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').

\$\endgroup\$
6
  • 1
    \$\begingroup\$ de2bi(n) can replace dec2bin(n)=='1' if toolboxes are allowed. \$\endgroup\$
    – Orhym
    Commented Aug 2, 2018 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 R
    Commented Aug 2, 2018 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 R
    Commented Aug 2, 2018 at 14:41
  • \$\begingroup\$ @sundar Thanks, included \$\endgroup\$
    – Wolfie
    Commented Aug 2, 2018 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
    Commented Aug 3, 2018 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).

\$\endgroup\$
0
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.

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

\$\endgroup\$
1
  • \$\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
    Commented Feb 19, 2020 at 23:01
2
\$\begingroup\$

Forth (gforth), 41 bytes

: f 1 swap 63 for 0 d2* m+ next + 2 mod ;

Try it online!

A function with signature ( u -- 0-or-1 ), that is, one that takes a cell-sized integer from the stack and gives a 0 (not evil) or 1 (evil) on the stack. gforth's native boolean is -1 (true) and 0 (false), but any nonzero value is recognized as true, just like many other languages.

Unlike the answer to a very similar challenge, the FP trick seems to fail to save bytes here.

How it works

: f ( u -- 0-or-1 ) \ Declare function f
  1 swap 63 for     \ Store a 1 under u, and loop 64 times ( 1 u )
                    \ The 1 is bit-count + 1
    0               \   Push a 0 (i.e. cast to unsigned double-cell int)
    d2*             \   Shift double-cell int left once ( 1 u' 0-or-1 )
                    \   In effect, shift MSB of u into the top
    m+              \   Add double [1 u'] and single [0-or-1]
                    \   In effect, add the bit to the bit-count
  next              \ End loop ( bc+1 0 )
  + 2 mod           \ Remove the dummy 0 at the top, and take modulo 2
;
\$\endgroup\$
2
\$\begingroup\$

Arn, 8 bytes

›1¢|▬║~Ô

Explained

Unpacked: !(+\(:_b%2

! Boolean not
  ( Expression
    +\ Fold with addition
      ( Expression
        :_ Format implicit variable _ (initialized as stdin)...
          b ... to binary
        %2 Modulo 2
      ) Implicit, can be removed
  ) Implicit, can be removed
\$\endgroup\$
2
\$\begingroup\$

Scala, 24 bytes

_.toBinaryString.sum%2<1

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Husk, 5 4 bytes

¬F≠ḋ

Try it online!

-1 byte from Jo King.

\$\endgroup\$
0
2
\$\begingroup\$

tinylisp, 47 bytes

(load library)
(d E(q((N)(even?(sum(to-base 2 N

Try it online!

Straightforward solution, thanks to useful library functions.

\$\endgroup\$
2
\$\begingroup\$

Wolfram Language (Mathematica), 27 bytes

This is my first ever post on code golf, and I am doing this mostly to hone my Mathematica skills. Any suggestions are greatly appreciated!

2∣Tr[IntegerDigits[#,2]]&

Try it online!

This works by checking the parity of the base-2 digit sum (also called the digital sum). The method is slightly different than the other Mathematica answers.

Edit: I was able to save three bytes by changing Total -> Tr. This was found in the tips page suggested in the comments.

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to Code Golf, and nice first answer! Be sure to check out our Tips for Golfing in Mathematica page for further ways you may be able to golf your code! \$\endgroup\$
    – pxeger
    Commented Jun 15, 2022 at 20:01
  • \$\begingroup\$ Thank you for the tips page. I was not aware of that. \$\endgroup\$
    – dirvine
    Commented Jun 15, 2022 at 20:13
2
\$\begingroup\$

Python 3.10, 25 bytes

lambda x:~x.bit_count()%2

It's the same number of char that Lynn's answer but with a totally "new idea".
The .bit_count() is new in Python 3.10 and returns the number of 1. So with that, you can make it 25 bytes.

Note: I can't put a "Try It Online" because their version of Python is 3.7.8
But thank's to @pxeger's comment: You can test the code here

\$\endgroup\$
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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