Is this number evil?

38

4

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.

Amphibological

Posted 2018-08-01T15:08:21.957

Reputation: 1 394

Sandbox. – Amphibological – 2018-08-01T15:09:30.457

2Related (XOR-ing every binary digit is the same as taking the sum modulo-2). – Kevin Cruijssen – 2018-08-01T15:25:03.913

4

Possible duplicate of Count the number of ones in an unsigned 16-bit integer

– Beta Decay – 2018-08-01T17:11:04.210

My language (R) only has 32-bit signed integers; beyond that it switches by default to a double; is it OK if we run out of precision? – Giuseppe – 2018-08-01T19:56:08.203

@Giuseppe no problem, as long as your program works for 32 bits you're fine. – Amphibological – 2018-08-01T19:56:57.850

@BetaDecay I have tried to address that above. I personally don't think this is a duplicate though. – Amphibological – 2018-08-01T20:01:23.017

This is a dupe because you can take any of those answers and bolt mod 2 on the end – Beta Decay – 2018-08-01T20:25:37.163

2@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 – 2018-08-01T20:29:53.053

@BetaDecay side note: is there meta consensus as to what constitutes a duplicate? – Amphibological – 2018-08-01T20:35:47.113

A challenge is a dupe if a trivial change can be made to answers of the original challenge to make them suitable for the duplicate challenge. Backwards compatibility is AFAIK not counted – Beta Decay – 2018-08-01T20:44:22.640

@BetaDecay is there anywhere on meta that says that or not? Also, if this really is a dupe, what should I do? I still think this challenge can invite some different approaches. – Amphibological – 2018-08-01T20:46:18.447

Quick question: does the output need to be true/false or can it be 1/0? – Robert S. – 2018-08-01T20:54:37.187

@RobertS. any two values that are considered truthy and falsy in your language are fine. – Amphibological – 2018-08-01T20:55:47.410

Related: How on earth did llhuii output the Evil Numbers in 42 bytes of Python?

– nwellnhof – 2018-08-01T22:53:12.960

14I believe that 666 => False should be a test case. – user2390246 – 2018-08-02T10:38:27.870

@JoKing if by broken you mean the random HTML at the bottom, that's due to misformatted answers. I've tried to edit or comment on all of those. – Amphibological – 2018-08-04T15:45:28.177

Why would you call this an "evil" number. There is a long standing tradition to declare the binary representation of the number as being "even parity". – Michael Karas – 2018-08-04T18:23:27.783

@user2390246 finally, done. ;) – Amphibological – 2018-08-04T22:17:45.240

Leaderboard says "message": "Uncaught TypeError: Cannot read property 'forEach' of undefined", "filename": "https://stacksnippets.net/js", "lineno": 122, "colno": 18" – Simon Forsberg – 2018-08-05T13:56:28.157

@SimonForsberg sorry, that doesn't happen for me...i don't know why it's happening for you. – Amphibological – 2018-08-05T14:30:09.890

1

@Amphibological I found out why, I'm getting "too many requests from this IP, more requests available in 57696 seconds" back from the Stack Exchange API. I think I know who to blame though.

– Simon Forsberg – 2018-08-05T17:04:34.083

1Yes, 666 is not evil, but 616 is. More evidence corroborating Papyrus 115! – aschepler – 2018-08-07T11:41:20.043

Answers

36

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.

cschultz2048

Posted 2018-08-01T15:08:21.957

Reputation: 481

i like this but how does this work? my memory for assembly (6502 + arm) are that ors are bitwise with 2 operands – northern-bradley – 2018-08-01T20:00:55.563

2@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. – cschultz2048 – 2018-08-01T20:04:25.130

@northern-bradley: The P flag is the parity of the OR result, i.e. the horizontal-xor of all the bits, i.e. popcnt mod 2. x86 also has a parity flag (PF), but it's updated only from the low byte of the result even for wider operand-sizes like test eax,eax. So for x86 you'd probably popcnt eax, edi / and eax,1 / ret. (Fun fact: 8086 was designed to make source porting of 8080 asm trivial / doable by a machine. The start of x86: Intel 8080 vs Intel 8086?.)

– Peter Cordes – 2018-08-03T02:49:50.130

For x86-16, we can xor al,ah / ret (return value in PF), taking advantage of the same hardware feature in x86. I wrote this up as an answer.

– Peter Cordes – 2018-08-03T06:08:20.693

1

Is P allowed as per https://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.

– CJ Dennis – 2018-08-03T09:51:16.497

2Damn built-ins :P – Jo King – 2018-08-03T10:04:01.390

@CJDennis I'd argue that the use of the P flag is OK as per this answer. As for the 8-bit problem, would the following code work for a 16-bit value in A and B? xor B ret

– cschultz2048 – 2018-08-03T13:32:53.203

1@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. – CJ Dennis – 2018-08-03T13:55:34.007

@CJDennis Thanks for your suggestions. I edited the answer. – cschultz2048 – 2018-08-03T14:30:59.613

27

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

Arnauld

Posted 2018-08-01T15:08:21.957

Reputation: 111 334

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! – supafly – 2018-08-07T15:34:45.393

1@supafly I've added an explanation. And BTW: welcome to PPCG! – Arnauld – 2018-08-07T16:09:24.110

The processing is very clear now. Still, the idea/reasoning is really magic! Thank you for the explanation! – supafly – 2018-08-07T16:43:25.553

13

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.

Lynn

Posted 2018-08-01T15:08:21.957

Reputation: 55 648

Since this is Python 2, the code can be further shortened with the deprecated repr backtick syntax: lambda n:int(`n`,13)%2. Try it online!

– GarethPW – 2018-08-12T23:32:39.473

Yeah, had a bit of a brain fart there and forgot the purpose of int’s base argument. Whoops! – GarethPW – 2018-08-13T00:04:15.460

12

Japt -h!, 5 4 3 bytes

¤å^

Try it


Explanation

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

Shaggy

Posted 2018-08-01T15:08:21.957

Reputation: 24 623

@LuisfelipeDejesusMunoz, porting Kevin's 05AB1E solution also works out at 5 bytes, if you want to try for that. – Shaggy – 2018-08-01T15:21:59.757

¤¬x v this is kevin's answer – Luis felipe De jesus Munoz – 2018-08-01T15:28:19.223

@LuisfelipeDejesusMunoz, yup, that's it. – Shaggy – 2018-08-01T15:28:52.893

8

05AB1E, 4 bytes

bSOÈ

Try it online or verify all test cases.

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

Kevin Cruijssen

Posted 2018-08-01T15:08:21.957

Reputation: 67 575

8

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

auhmaan

Posted 2018-08-01T15:08:21.957

Reputation: 906

3Upvoted for the chuckle your "ungolfed" version gave me. – Jack Brounstein – 2018-08-02T17:02:44.513

8

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.

Kusalananda

Posted 2018-08-01T15:08:21.957

Reputation: 181

7

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

Giuseppe

Posted 2018-08-01T15:08:21.957

Reputation: 21 077

Why don't hardcode 31 instead of log2 ? Try it online!

– digEmAll – 2018-08-01T19:04:43.550

@digEmAll Which in turn means no need to define x

– JayCe – 2018-08-01T19:42:24.037

@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. – Giuseppe – 2018-08-01T19:58:31.553

Also intToBits supports only integer values up to 2^31-1 ;) – digEmAll – 2018-08-01T20:19:36.540

6

Stax, 4 bytes

:1|e

Run and debug it

:1|e Full program, implicit input-evaluation
:1   Count set bits
  |e Check if even

wastl

Posted 2018-08-01T15:08:21.957

Reputation: 3 089

6

R, 99 98 44 34 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

Robert S.

Posted 2018-08-01T15:08:21.957

Reputation: 1 253

2I don't know R too well, but I'm pretty sure ==0 can be <1 :) – Kevin Cruijssen – 2018-08-01T15:26:15.240

@KevinCruijssen You're right. Should have seen that. Thanks! – Robert S. – 2018-08-01T15:29:14.087

143 bytes? – ngm – 2018-08-01T16:44:14.407

@ngm That works! Didn't think it would be that simple. Thanks. I'm getting 44 bytes though. – Robert S. – 2018-08-01T16:53:17.423

1

Nice! 34 bytes is possible

– Giuseppe – 2018-08-01T16:58:59.130

@Giuseppe Wow! I've definitely learned some R code golf tips from this one. Thanks. – Robert S. – 2018-08-01T17:04:17.597

1

This works as well I think : 32 bytes But requires a bit of an explanations :)

– digEmAll – 2018-08-01T18:23:54.027

@digEmAll This is a good suggestion for Giuseppe's answer! – Robert S. – 2018-08-01T18:30:39.697

Oh, I didn't notice that answer... I'll post there – digEmAll – 2018-08-01T19:02:50.823

1it's easy to turn this into a full program for some more bytes – JayCe – 2018-08-01T19:45:30.083

@JayCe Easy enough! Thanks. – Robert S. – 2018-08-01T19:49:47.147

5

C (gcc), 36 bytes

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

Try it online!

Method from K&R https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan

Must be compiled with optimization level 0

vazt

Posted 2018-08-01T15:08:21.957

Reputation: 311

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? – villapx – 2018-08-01T21:52:10.190

1Doesn't work with -O. – nwellnhof – 2018-08-01T23:19:20.157

2

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

– Borka223 – 2018-08-02T19:09:04.160

@nwellnhof @villapx Compiles fine on my 7.3.0 - just make sure you're not missing the -O0 compiler flag. – None – 2018-08-02T21:02:59.113

@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 – 2018-08-02T21:54:46.987

I assume we are calling the function with only n? If so, c is uninitialised. – gastropner – 2018-08-03T09:14:20.053

@gastropner Thanks. Interesting bug - it had 50/50 chance of working properly. If the uninitialized value was an even number (and not large enough to overflow), it would work fine – vazt – 2018-08-03T14:13:39.193

5

Wolfram Language (Mathematica), 24 22 bytes

2∣DigitCount[#,2,1]&

Try it online!

Jonathan Frech

Posted 2018-08-01T15:08:21.957

Reputation: 6 681

2∣ is an improvement on EvenQ. Try it online! – Misha Lavrov – 2018-10-21T04:31:31.387

4

PHP, 37 36 bytes

<?=1&~substr_count(decbin($argn),1);

To run it:

echo '<input>' | php -nF <filename>

Or Try it online!

Prints 1 for true, and 0 for false.

-1 byte thanks to Benoit Esnard!

Ethan

Posted 2018-08-01T15:08:21.957

Reputation: 435

1I think you can save one byte by removing the modulo operation: <?=1&~substr_count(decbin($argn),1);. This one also prints 0 for false. – Benoit Esnard – 2018-08-02T11:45:17.450

Thanks @BenoitEsnard! That's very clever, I've updated my answer :) You learn something new every day! – Ethan – 2018-08-02T12:09:42.647

4

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.

sundar - Reinstate Monica

Posted 2018-08-01T15:08:21.957

Reputation: 5 296

4

INTERCAL, 90 65 63 bytes

DOWRITEIN:1
DO:2<-'#0$#65535'~?':1~:1'
DOREADOUT:2
PLEASEGIVEUP

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

Ethan

Posted 2018-08-01T15:08:21.957

Reputation: 271

3

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

Triggernometry

Posted 2018-08-01T15:08:21.957

Reputation: 765

1No fewer bytes but lambda n:~bin(n).count('1')&1 replaces the modular division with something potentially less expensive. – cdlane – 2018-08-02T06:22:42.583

3

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.

Conor O'Brien

Posted 2018-08-01T15:08:21.957

Reputation: 36 228

:| i have no words – ASCII-only – 2018-08-06T06:51:21.110

@ASCII-only quite succinct, eh? c: – Conor O'Brien – 2018-08-06T06:55:27.043

3

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.

Sophia Lechner

Posted 2018-08-01T15:08:21.957

Reputation: 1 200

3

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

Annyo

Posted 2018-08-01T15:08:21.957

Reputation: 231

Welcome to PPCG! You may be able to save a byte by golfing != to - and another four by golfing return to i=. – Jonathan Frech – 2018-08-02T12:17:46.477

@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? – sundar - Reinstate Monica – 2018-08-02T16:26:47.420

1It is a gcc specific undefined behaviour abuse on optimization level O0. – Jonathan Frech – 2018-08-02T17:45:04.110

By switching to K&R C, you can get it down to 23 bytes (very impressive!) Try it online!

– ErikF – 2018-08-02T22:01:27.013

@JonathanFrech: why do people insist on using that stupid gcc -O0 hack? It's not like the length of a language's total boilerplate matters much when comparing implementations. Also, it makes it more interesting to choose between return vs. call-by-reference (updating *i in place). I'd rather write C or C++ answers, not un-optimized-gcc-only answers, because un-optimized-gcc isn't a very useful language. – Peter Cordes – 2018-08-03T06:25:19.243

@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. – Jonathan Frech – 2018-08-03T12:42:13.500

@JonathanFrech: When I golf in C, I like to golf in ISO C89 and write portable code that works with gcc -O0 or clang -O3. If there's something interesting to be gained by assuming 2's complement or something, then I'll mention it. I know calling it "stupid" is going a bit far, but I really dislike it. Partly because I like looking at compiler asm output, and -O0 is dumb. I don't think this was the intent of the "works on at least one implementation". An output arg like Tips for golfing in C can work in some cases.

– Peter Cordes – 2018-08-03T13:00:31.493

3

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

Peter Cordes

Posted 2018-08-01T15:08:21.957

Reputation: 2 810

3

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

CarManuel

Posted 2018-08-01T15:08:21.957

Reputation: 31

Welcome to PPCG, and good first answer! – mbomb007 – 2019-02-06T20:00:54.593

2

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.

Kevin Cruijssen

Posted 2018-08-01T15:08:21.957

Reputation: 67 575

1n.toString(n,2) saves 4 bytes. – Okx – 2018-08-01T15:55:10.563

@Okx Not sure how I forgot about that one, lol.. Thanks! ;) – Kevin Cruijssen – 2018-08-01T17:39:12.713

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. – Mario Ishac – 2018-08-01T19:20:43.777

1

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

– Kevin Cruijssen – 2018-08-01T21:02:19.180

2

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

Govind Parmar

Posted 2018-08-01T15:08:21.957

Reputation: 828

@ceilingcat Good catch! – Govind Parmar – 2018-08-01T20:01:39.503

1Suggest inc eax instead of not eax. Also may want to mention that this requires a processor with support for the popcnt instruction. – ceilingcat – 2018-08-01T20:15:56.803

1

also you do not have to take arg from stack. see allowed calling conventions https://codegolf.stackexchange.com/a/161497/17360 (Peter Cordes's more in-depth answer https://codegolf.stackexchange.com/a/165020/17360)

– qwr – 2018-08-01T20:43:30.050

1

Note that you may return a boolean in FLAGS https://stackoverflow.com/a/48382679/3163618

– qwr – 2018-08-01T20:47:58.260

Shouldn't 666 be a test case? – Arcanist Lupus – 2018-08-01T21:08:36.050

@ArcanistLupus 666 is not evil; 616 is evil

– ceilingcat – 2018-08-01T22:04:57.473

You can skip the inversion if you decide that 0 means truthy and 1 means falsy, or returning a result in EFLAGS could be easier to justify (either PF or ZF). But yeah, the main saving would be a better calling convention. e.g. make this an x86-64 answer and the arg will be in edi (x86-64 System V) or ecx (Windows x64). Or simply use a 32-bit fastcall convention. – Peter Cordes – 2018-08-03T02:54:42.580

2

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

reffu

Posted 2018-08-01T15:08:21.957

Reputation: 1 361

2

Perl 6, 21 bytes

*.base(2).comb(~1)%%2

Test it

Expanded:

*\        # WhateverCode lambda (this is the parameter)
.base(2)  # Str representing the binary
.comb(~1) # find the "1"s

%% 2      # is the count of "1"s divisible by 2?

Brad Gilbert b2gills

Posted 2018-08-01T15:08:21.957

Reputation: 12 713

*.base(2)%9%%2 – Jo King – 2018-08-01T19:56:06.843

Ah, that doesn't work for digits with more than 9 bits... – Jo King – 2018-08-01T20:18:38.397

1{:3(.base(2))%%2} – nwellnhof – 2018-08-01T22:41:30.510

2

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

Eric Canam

Posted 2018-08-01T15:08:21.957

Reputation: 21

Since "" is the default third argument for SUBSTITUTE, you can save two bytes with =MOD(LEN(SUBSTITUTE(DEC2BIN(A1),0,)),2)=0 – Sophia Lechner – 2018-08-01T19:06:25.447

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 – 2018-08-01T19:36:34.700

(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 – 2018-08-01T19:48:39.183

@SophiaLechner, what version of Excel are you using? This doesn't seem to be the case in Excel 2013 – Eric Canam – 2018-08-01T19:50:15.950

@SophiaLechner Never mind, I see what you meant :) – Eric Canam – 2018-08-01T19:57:19.070

1

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 – 2018-08-02T17:29:16.447

2

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!

Jack Brounstein

Posted 2018-08-01T15:08:21.957

Reputation: 381

You can remove the spaces between the 1 and the or to save +1 byte. Nice solution! – Amphibological – 2018-08-02T00:22:37.127

Man, I thought I tried that. Good catch! – Jack Brounstein – 2018-08-02T02:05:46.607

2

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.

Neil

Posted 2018-08-01T15:08:21.957

Reputation: 95 035

2

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

Adám

Posted 2018-08-01T15:08:21.957

Reputation: 37 779

2

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

Adám

Posted 2018-08-01T15:08:21.957

Reputation: 37 779

Nice one! the boring approach is 9 bytes: 2|1+1#.#: – Conor O'Brien – 2018-08-01T21:21:33.850

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 – 2018-08-01T22:45:28.620

@ConorO'Brien Boring trumps incorrect. – Adám – 2018-08-02T07:43:35.583

@FrownyFrog Fixed. – Adám – 2018-08-02T07:43:47.680

2

Ruby, 32 29 28 27 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.

akostadinov

Posted 2018-08-01T15:08:21.957

Reputation: 211

%2==0 saves 1 byte. – Reinstate Monica -- notmaynard – 2018-08-02T14:02:41.920

@iamnotmaynard, thank you, thank you! I couldn't accept that python solution would be shorter :) wow, now I see it got 27 :/ – akostadinov – 2018-08-02T16:22:30.640

Instead of %2==0 can't you do something like %2<1 to save a byte? – auhmaan – 2018-08-02T16:28:57.200

@auhmaan Oh yeah, even better. – Reinstate Monica -- notmaynard – 2018-08-02T16:31:38.190

@auhmaan, my hero, now we are on par with python. I wonder though, wasn't there a rule to return boolean by 1 or 0 if desired? Or only for languages where these evaluate to true/false by convention? – akostadinov – 2018-08-02T16:43:16.433

The challenge specifically says that it wants a truthy or falsey value, which the current consensus on Meta defines based on how a conditional handles it, so for non-evil numbers your Ruby code would have to output false or nil. (Note that's language specific, so it's OK that my Python answer returns 0 or 1.) Sometimes challenges just ask for you to output one of two distinct values, though, in which case 1 and 0 would be fine.

– Jack Brounstein – 2018-08-02T17:00:29.063

@JackBrounstein, thank you very useful. I couldn't find a list of officially accepted rules for the site :/ – akostadinov – 2018-08-02T17:14:17.677

1("%b"%n).count(?1)%2 is the same as ("%b"%n).sum%2 – G B – 2020-02-12T08:20:33.743

@GB, wow, nice suggestion. I can't understand why such method went into the API but works for the task at hand. – akostadinov – 2020-02-12T19:51:42.297

2

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

Wolfie

Posted 2018-08-01T15:08:21.957

Reputation: 221

1de2bi(n) can replace dec2bin(n)=='1' if toolboxes are allowed. – Orhym – 2018-08-02T01:19:05.853

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 – 2018-08-02T14:35:51.840

1I 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 – 2018-08-02T14:41:12.633

@sundar Thanks, included – Wolfie – 2018-08-02T14:59:09.817

@(n)~mod(sum(de2bi(n)),2) works with toolboxes. – Brain Guider – 2018-08-03T10:11:58.590

1@Ander Cheers, orhym had suggested this too but don't know why I didn't add it in. – Wolfie – 2018-08-03T10:27:50.833

2

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

Digital Trauma

Posted 2018-08-01T15:08:21.957

Reputation: 64 644

2

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!

Bubbler

Posted 2018-08-01T15:08:21.957

Reputation: 16 616

2

Java (JDK 10), 26 bytes

-6 bytes thanks to Roberto Graham

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

Try it online!

Okx

Posted 2018-08-01T15:08:21.957

Reputation: 15 025

20 bytes Try it online!

– Roberto Graham – 2018-08-06T17:11:17.967

@RobertoGraham Thanks, forgot you can call static methods on a variable. – Okx – 2018-08-06T17:13:33.753

2

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!

F.Carette

Posted 2018-08-01T15:08:21.957

Reputation: 141

47 bytes using a for instead of a while. And welcome to PPCG! – Charlie – 2018-08-02T12:59:12.657

Sorry, 45 bytes using your XOR solution.

– Charlie – 2018-08-02T13:05:00.600

@Charlie: Edited, thanks for the tip – F.Carette – 2018-08-02T14:22:08.057

2

JavaScript (Babel Node), 39 bytes

-1 Bytes thnks to @OMᗺ =D

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

Try it online!

Luis felipe De jesus Munoz

Posted 2018-08-01T15:08:21.957

Reputation: 9 639

2

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!

an earwig

Posted 2018-08-01T15:08:21.957

Reputation: 141

1A 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 – 2018-08-02T16:13:43.337

2Also, 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 – 2018-08-02T16:14:53.923

2

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!

Borka223

Posted 2018-08-01T15:08:21.957

Reputation: 311

2

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

GalladeGuy

Posted 2018-08-01T15:08:21.957

Reputation: 101

Good point! I'll edit my answer! – GalladeGuy – 2018-08-03T16:51:33.380

2

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.

Helen

Posted 2018-08-01T15:08:21.957

Reputation: 125

2

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.

Misha Lavrov

Posted 2018-08-01T15:08:21.957

Reputation: 4 846

2

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

Jo King

Posted 2018-08-01T15:08:21.957

Reputation: 38 234

wow, nice. also, close :(

– ASCII-only – 2019-01-30T05:01:15.273

also -1 nondeterministic :P – ASCII-only – 2019-01-30T05:03:22.420

1Also, haha, we came up with the same solution of checking for 1 – ASCII-only – 2019-01-30T05:04:21.273

:D tie, if it works. as an added bonus, it's deterministic – ASCII-only – 2019-01-30T05:10:04.607

@ASCII-only i had a leftover unnecessary term, so -3 bytes :). I was wondering what was non-deterministic, but it turns out the d+0f->f rule goes off whenever it wants. Still technically deterministic since it doesn't affect anything – Jo King – 2019-01-30T05:14:22.103

1

well. if i invert output then 103 :P, and 99 without determinism

– ASCII-only – 2019-01-30T05:23:07.060

I see though that you don't use BMO's method of having a state atom. Also, you might wanna check if aliasing (e.g. a+0c->g) makes it shorter – ASCII-only – 2019-01-30T05:25:05.023

I've sort of been winging it? The non-deterministic routes remind me a bit of Lost – Jo King – 2019-01-30T05:26:11.633

Haha, yeah. I'm sure BMO has been winging it too lol – ASCII-only – 2019-01-30T05:26:56.667

Darn, tie again :P – ASCII-only – 2019-01-30T05:37:40.057

@ASCII-only You can switch most rules with flag1 + ... -> flag1 + ... to 0flag2 + ... -> ... to save a byte for each rule affected. 95 bytes

– Jo King – 2019-01-30T05:45:08.010

Let us continue this discussion in chat.

– ASCII-only – 2019-01-30T05:47:45.320

2

05AB1E, 4 bytes

b1¢È

Try it online!

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

Jackson

Posted 2018-08-01T15:08:21.957

Reputation: 101

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 – 2020-02-19T23:01:00.843

2

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.

dana

Posted 2018-08-01T15:08:21.957

Reputation: 2 541

2

x86-16 machine code, 3 bytes

32 C4     XOR  AL, AH     ; PF = (AX >> 8) XOR AL
C3        RET             ; return to caller

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:

enter image description here

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

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

640KB

Posted 2018-08-01T15:08:21.957

Reputation: 7 149

1

Jelly, 4 bytes

BS2ḍ

Try it online!

Erik the Outgolfer

Posted 2018-08-01T15:08:21.957

Reputation: 38 134

1

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.

Phlarx

Posted 2018-08-01T15:08:21.957

Reputation: 1 366

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 – 2018-08-02T16:16:44.510

@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 – 2018-08-02T16:35:03.610

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 – 2018-08-02T17:08:11.663

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 – 2018-08-02T17:16:55.750

@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 – 2018-08-02T18:11:26.513

Oh, and regarding the difficulty in TIO, it doesn't currently interpret escape sequences like \xe4 in any special way. You'd have to do something clever with a heredoc or similar instead.

– Phlarx – 2018-08-02T18:22:38.740

Makes sense, thanks! I've missed playing around with simple chips and circuits, and this language seems like it captures the feel of that pretty well, so I'll definitely be checking out more of it later. – sundar - Reinstate Monica – 2018-08-03T12:19:45.750

1

Pyth, 6

!xFjQ2

Explanation

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

Digital Trauma

Posted 2018-08-01T15:08:21.957

Reputation: 64 644

1

Bash, 97 64 42 39 Bytes

Thanks ilkkachu

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

Try it online!

jesse_b

Posted 2018-08-01T15:08:21.957

Reputation: 111

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 – 2018-08-02T00:16:37.387

@DigitalTrauma: Thanks. I shortened it up some, still not as short as yours though. – jesse_b – 2018-08-02T14:00:55.367

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 – 2018-08-02T19:34:56.733

1

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

remoel

Posted 2018-08-01T15:08:21.957

Reputation: 511

1

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

Fatalize

Posted 2018-08-01T15:08:21.957

Reputation: 32 976

1

Pari/GP, 21 bytes

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

Try it online!

alephalpha

Posted 2018-08-01T15:08:21.957

Reputation: 23 988

+1. Beats the faster n->1-hammingweight(n)%2. – Charles – 2018-08-02T15:05:12.710

1

Haskell, 37 bytes

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

Try it online!

ბიმო

Posted 2018-08-01T15:08:21.957

Reputation: 15 345

1

Common Lisp, 30 bytes

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

Try it online!

djeis

Posted 2018-08-01T15:08:21.957

Reputation: 281

1

brainfuck, 104 bytes

+>,[++++>-[<->-----],]<[[-[[<]<]++++++++++<]<<[<,+<]++[->>]>,>[<<]>[>]<]<<<+[<[-<<+>>]<]<+[[<]++[->]<]<.

Try it online!

Outputs a null byte for false, 0x1 for true. Uses the convert to binary trick twice, once to get the sum of binary digits and the other to check if that number is even or odd by getting the last binary digit.

Jo King

Posted 2018-08-01T15:08:21.957

Reputation: 38 234

1

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}

Kjetil S.

Posted 2018-08-01T15:08:21.957

Reputation: 1 049

1

perl -E, 39 bytes

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

user73921

Posted 2018-08-01T15:08:21.957

Reputation:

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.

Jo King

Posted 2018-08-01T15:08:21.957

Reputation: 38 234

1

Rust, 24 bytes

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

Try it online!

Noskcaj

Posted 2018-08-01T15:08:21.957

Reputation: 421

1

Pyt, 5 4 bytes

Ħ⁺2%

Try it online!

Explanation:

      Implicit input
Ħ     Convert into binary and count the 1s
 ⁺    Increment
  2%  Mod 2

u_ndefined

Posted 2018-08-01T15:08:21.957

Reputation: 1 253

1

K (oK), 13 12 bytes

-1 byte thanks to ngn

~2!+/(99#2)\

Try it online!

Thaufeki

Posted 2018-08-01T15:08:21.957

Reputation: 421

10= -> ~­­­­ – ngn – 2018-10-24T22:48:58.410

1

PowerShell, 55 52 bytes

-3 bytes thanks to @mazzy

1-([Convert]::ToString("$args",2)-replace0).Length%2

Try it online!

Takes input as an integer from a command-line parameter.

Gabriel Mills

Posted 2018-08-01T15:08:21.957

Reputation: 778

:) Try it online!

– mazzy – 2019-01-30T07:37:15.297

1

PowerShell, 44 bytes

param($n)for(;$n;$n=$n-shr1){$e+=$n%2}1-$e%2

Try it online!

Straightforward counting.

mazzy

Posted 2018-08-01T15:08:21.957

Reputation: 4 832

1

Regex (ECMAScript), 37 33 bytes

Edit: Down 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!

^
(
    # 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.

The PCRE version of this is especially concise at 26 bytes: ^((((x*)(?=\4$))*+x){2})*$

Deadcode

Posted 2018-08-01T15:08:21.957

Reputation: 3 022

1^((((.*)(?=\4$))*.(.*)(?=\5$)){2})*$ is only 36 bytes. – Neil – 2019-02-05T10:34:30.657

1

Brain-Flak, 76 bytes

{({<([()]{})>{(<([()]{})>)()}{}}<(()[[]]{}){<>([(){}])(<><{}>)}{}>)}<>({}())

Try it online!

Explanation

{
  ({ Divide by two
    <([()]{})>
    {(<([()]{})>)()}{}
  }
  # Invert other side if 1 is the next digit
  <(()[[]]{}){<>([(){}])(<><{}>)}{}>)
}
<>({}()) # Process output

MegaTom

Posted 2018-08-01T15:08:21.957

Reputation: 3 787

1

APL(NARS), 29 chars, 58 bytes

{⍵≤0:0⋄∼2∣+/{(2⍴⍨⌊1+2⍟⍵)⊤⍵}⍵}

test:

  f←{⍵≤0:0⋄∼2∣+/{(2⍴⍨⌊1+2⍟⍵)⊤⍵}⍵}
  f 3
1
  f 11
0
  f 777
1

RosLuP

Posted 2018-08-01T15:08:21.957

Reputation: 3 036

1

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
;

Bubbler

Posted 2018-08-01T15:08:21.957

Reputation: 16 616

1

ink, 53 bytes

=e(n)
~temp o=0
-(i)~o+=n%2
~n=n/2
{n:->i}{1-o%2}->->

Try it online!

Counts bits.

Sara J

Posted 2018-08-01T15:08:21.957

Reputation: 2 576

1

GolfScript, 13 bytes

2 base{+}*2%!

Try it online!

This can't really be golfed much harder in this language, I don't believe. Maybe a character somewhere? But you absolutely need to use "2 base", and that takes up half the program, which stinks. I did find a second, different solution though -

2 base[1]/,2%

Try it online!

Here's the explanation for both;

2 base        #Convert into binary
#--------------------------#
      {+}*    #Add up all the 1s and 0s
          2%  #Mod 2
            ! #If even, make 1. If odd, make 0.
#--------------------------#
      [1]/    #Divide the binary across the 1s, this leaves 1 more array than the number of 1s
          ,   #Count the off-by-one array
           2% #If it mods to 1, it's even (because off by one), if not, it's 0. Neat!

If I could say "0 is truthy, and 1 is falsy", then I could save a character on the first one, but that would just be silly!

Mathgeek

Posted 2018-08-01T15:08:21.957

Reputation: 408

This gives an error for input 0 – Pseudo Nym – 2020-02-20T21:16:37.453

Works fine for me - are you putting it in "input" or "header"? Header is where GS takes in input - straight into the stack. – Mathgeek – 2020-02-21T13:15:40.927

That was the issue. – Pseudo Nym – 2020-02-21T14:59:35.957

1

Python 3, 30 bytes

lambda n:bin(n).count('1')%2<1

Try it online!

Thanks to @Stephen for saving a byte!

Dion

Posted 2018-08-01T15:08:21.957

Reputation: 35

2You can save a byte with <1 instead of ==0. – Stephen – 2020-02-19T20:50:59.503

...lambda n:~bin(n).count('1')%2 would save one more (still not gonna beat lambda n:int(bin(n),13)%2 though :)) – Jonathan Allan – 2020-02-20T01:07:07.990

1

Java, 29 28 26 64 63 49bytes

static boolean c(int r){return r==0||c(r*2)^r<0;}

Try it online!

Seems to work. Nice bit of recursion. It'd be 26 25 23 if I could rename the outer class. Perhaps get a better reference to itself.

Old and boring saves 14 bytes, by Jo King. (If you really want traditional and do-it-by-hand r->0<((r=(r=(r=(r^=r<<16)^r<<8)^r<<4)^r*4)^r*2) for 47 (may have the odd byte of flab).

Tom Hawtin - tackline

Posted 2018-08-01T15:08:21.957

Reputation: 127

@JoKing I don't have a knowledge of all the meta posts the rules are covered on. – Tom Hawtin - tackline – 2020-02-21T12:39:07.753

0

Yabasic, 81 bytes

Input""n
s$=Bin$(n)
v=1
For i=1To Len(s$)
If Mid$(s$,i,1)="1"Then v=!v Fi
Next
?v

Try it online!

Taylor Scott

Posted 2018-08-01T15:08:21.957

Reputation: 6 709

0

Charcoal, 7 bytes

§10Σ↨N²

Try it online! Link is to verbose version of code. Explanation:

     N  Input number
    ↨ ² Convert to base 2
   Σ    Sum of digits
§10     Cyclically index into literal string `10`
        Implicitly print

Neil

Posted 2018-08-01T15:08:21.957

Reputation: 95 035

0

Stacked, 15 bytes

[bits sum 2%0=]

Try it online!

Checks whether or not the sum of the bits of the input mod 2 (2%) is 0 (0=).

Conor O'Brien

Posted 2018-08-01T15:08:21.957

Reputation: 36 228

0

C# (.NET Core), 58 bytes

n=>System.Convert.ToString(n,2).Replace("0","").Length%2<1

Try it online!

I could do something similar to the Java answer with

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

That's 45 bytes but then I would need to add another 18 for using System.Linq;. So I needed to find another approach.

Charlie

Posted 2018-08-01T15:08:21.957

Reputation: 11 448

0

Red, 57 bytes

func[n][s: on until[if n % 2 = 1[s: not s]1 > n: n / 2]s]

Try it online!

Galen Ivanov

Posted 2018-08-01T15:08:21.957

Reputation: 13 815

0

SAS, 35 bytes

e=1-mod(count(put(i,binary.),1),2);

This expression takes a variable i as input and populates the result in a new variable, e. It relies on implicit conversion from character to numeric when specifying which digit to count.

user3490

Posted 2018-08-01T15:08:21.957

Reputation: 809

0

Julia 0.6, 20 bytes

n->count_ones(n)%2<1

Try it online!

sundar - Reinstate Monica

Posted 2018-08-01T15:08:21.957

Reputation: 5 296

0

dc, 27 bytes

0sb[2~lb+sbd1<a]dsaxlb1++2%

Try it online!

Instead of accumulating the bits in register b, we can also leave them on the stack (replace lb+sb by r) which essentially converts the input to binary, push 1, sum the stack and do the mod 2. But it's the same byte-count:

[2~rd1<a]dsax1[+z1<a]dsax2%

Try it online!

Explanation

Register b = 0, divmod on ToS, add remainder to b and loop until ToS is less or equal to 1, then compute ToS + b + 1 mod 2:

0sb[2~lb+sbd1<a]dsaxlb1++2%  # example input 5                     |  stack
0sb                          # initialize register b with 0        |  5
   [2~lb+sbd1<a]             # push the string [..]                |  [2~lb+sbd1<a]
                dsa          # duplicate & store it to register a  |  [2~lb+sbd1<a]
                   x         # execute the string*                 |  1
                    lb       # push register b                     |  1 1
                      1+     # increment by 1                      |  2 1
                        +    # add                                 |  3
                         2%  # modulo 2                            |  1

# Recursively called string:
2~lb+sbd1<a  # recursively called string   |  5
2~           # divmod 2                    |  1 2
  lb         # push register b             |  0 1 2
    +        # add                         |  1 2
     sb      # store register b            |  2
       d     # duplicate                   |  2 2
        1<   # if top (popped) is > 1:
          a  # | execute register a        |  2

ბიმო

Posted 2018-08-01T15:08:21.957

Reputation: 15 345

0

Python 3, 69 53 39 bytes

print(bin(int(input())).count('1')%2<1)

Works by using the built in python binary to converter, bin(), on the input, then counts the number of ones in there, checks if it is equal to 0 mod 2, and prints the result (outputs True/False).

Probably needs some more golfing, but this was my first whirl.

Try it online!

heather

Posted 2018-08-01T15:08:21.957

Reputation: 219

You can't assume inputs preassigned to a variable, though you can use a lambda: lambda x:1if len([i for i in bin(x)[2:]if i=='0'])%2==0else 0 which is shorter anyways (I included some basic golfing).

– ბიმო – 2018-08-02T19:25:15.257

Some more golfing on your approach (using that b has a higher ascii-codepoint than '0') leaves you with: lambda x:len([1for i in bin(x)if'0'<i])%2

– ბიმო – 2018-08-02T19:31:14.590

@OMᗺ you should probably post that as your own answer, as it's such a better approach than mine. I'd feel bad taking credit for it =) – heather – 2018-08-02T19:56:38.540

I won't - there are already shorter ones, but your submission still uses a preassigned variable as input which is not allowed.

– ბიმო – 2018-08-02T20:17:31.760

@OMᗺ fixed by switching to input() – heather – 2018-08-02T20:24:30.260

@JoKing thank you, I have done so. – heather – 2018-08-03T15:18:40.973

0

><>, 28 22 bytes

-6 bytes thanks to Jo King

:?!v:2%:@-$?:2,
%2l<;n

Code: 22 bytes
Input: put onto the stack using the -v command line argument
Output: 0 means not evil, 1 means evil

Try it online!

Pseudocode

This is a highly abstracted summary of what the program does.
The interpreter puts the input value into n at startup.

l := 1

while n ≠ 0 do:
  m := n mod 2
  if m ≠ 0 then:
    l := l + 1
  n := (n - m) / 2

print l mod 2

Borka223

Posted 2018-08-01T15:08:21.957

Reputation: 311

0

Scala, 39 bytes

readInt.toBinaryString.count('1'==)%2<1

Try it online

This can be run in a Scala console, after which the user has to input the integer and press enter.

Zoltán

Posted 2018-08-01T15:08:21.957

Reputation: 101

1Welcome to PPCG! – Luis felipe De jesus Munoz – 2018-08-03T13:56:44.313

1This submission seems to be a snippet which is disallowed. Please change your submission to either a full program or a function definition. – Jonathan Frech – 2018-08-03T14:04:30.217

Also, could you please make the title of your answer into a header (i.e. # Scala, 34 bytes) to fix the scoreboard? – Amphibological – 2018-08-04T15:43:04.937

@JonathanFrech I updated my answer, it now reads the input from user input, and is executable from the Scala console, or as a Scala script – Zoltán – 2018-08-06T07:56:08.900

0

Math++, 40 bytes

?>a
3+3*!a>$
b+a%2>b
_(a/2)>a
2>$
!(b%2)

SuperJedi224

Posted 2018-08-01T15:08:21.957

Reputation: 11 342

0

Scala, 43 41 bytes

def e(n:Int):Int=if(n>0)n%2^e(n/2)else 1

Test: https://scalafiddle.io/sf/VlU7nun/2

Kjetil S.

Posted 2018-08-01T15:08:21.957

Reputation: 1 049

Could you please add a comma after Scala in the title of your answer so it doesn't break the scoreboard? – Amphibological – 2018-08-04T15:38:47.157

0

Python 2, 46 bytes

lambda n:sum(int(d)for d in str(bin(n))[2:])%2

Outputs 1 for True or 0 for false

juniorRubyist

Posted 2018-08-01T15:08:21.957

Reputation: 875

You don't need to stringify the binary – Jo King – 2018-08-07T23:03:40.157

0

MATLAB 31 bytes

Anonymous function, use as f=@(n)...;f(3)

@(n)1-mod(sum(dec2bin(n)-48),2)

aaaaa says reinstate Monica

Posted 2018-08-01T15:08:21.957

Reputation: 381

0

CJam, 15 10 bytes

qi2b1e=2%!

Try it online!

Explanation
qi2b1e=2%! %whole code
qi         %Read input as number | Example stack: 10
  2b       %Convert to binary    | Example stack: 1010
    1e=    %Count ones           | Example stack: 22
       2%  %Mod 2                | Example stack: 0
         ! %Invert               | Example stack: 1

lolad

Posted 2018-08-01T15:08:21.957

Reputation: 754

0

AsciiDots, 86 64 bytes

/{&}\
|(*)?#-. 
*{>}:@1({+}*@:-{%}$#&
*{+}\#1/.^-/.-#2/
\-*.<#1)

Returns 1 if the number is evil, otherwise 0. Try it online!

Alion

Posted 2018-08-01T15:08:21.957

Reputation: 965

0

Pascal (FPC), 84 bytes

var n,s:word;begin read(n);repeat s:=n mod 2xor s;n:=n div 2until n=0;write(s=0)end.

Try it online!

No conversion to binary :(

AlexRacer

Posted 2018-08-01T15:08:21.957

Reputation: 979

0

Gol><>, 14 bytes

IW2SD@+$|~2%zh

Try it online!

Explanation:

IW2SD@+$|~2%zh  //Program for reference

I               //Input a integer
 W              //Loop until the number given is 0 (due to the int div 2 inside the loop)
  2SD           //  Push the div and mod of the remaining number by 2
     @          //  Rotate the top three elements on the stack (stack now is: curNumber/2, lastBitSet, bitCount)
      +         //  Add the bit count and the last bit flag
       $|       //  Swap the bitCount with the curNumer/2 and repeat until curNumber/2 == 0
         ~      //Remove the loop exit flag (0) 
          2%zh  //Check wether the bitCount is even, output & exit: 1 == truthy, 0 == falsy

Gegell

Posted 2018-08-01T15:08:21.957

Reputation: 81

0

05AB1E, 4 bytes

bSOÈ

Explanation:

bS    # Takes the input and coverts it into a list of binary digits
  O   # Sums all of the digits in this list
   È  # Checks if the sum is even

Try it online!

Brzyrt

Posted 2018-08-01T15:08:21.957

Reputation: 155

Exact duplicate of Kevin's answer.

– Grimmy – 2020-02-21T17:19:13.540

0

GolfScript, 14 bytes

2base{^}*!

Try it online!

Explanation:

2base         convert input to binary
     {^}*     xor all bits
         !    flip answer

Pseudo Nym

Posted 2018-08-01T15:08:21.957

Reputation: 181

0

chevron, 45 bytes

method borrowed from Lynn's python answer.

>:>^n
^n,10,2~x>>^n
b^n,13~x>>^n
^n%2>>^n
>^n

notes:

  • outputs :0 for falsy and :1 for truthy.

  • online interpreter defaults to printing the input at prompts, uncheck "print inp" to disable.

  • replace : with ^__ for no prompt.

Superloach

Posted 2018-08-01T15:08:21.957

Reputation: 71

0

C(GCC, clang), 33 bytes

f(n){return!__builtin_parity(n);}

Uses a compiler builtin, and as such works only with GCC and clang and whatever other compiler that implements it. Appears to work with all optimization settings.

Try it online! - GCC

Try it online! - clang

qookie

Posted 2018-08-01T15:08:21.957

Reputation: 81

-1

Python 3.7, 97 89 76 bytes

def h(s): 
    f=len(bin(s)[2:].replace("0",""))
    if f%2==0:print(f%2==0)

This is my code. I'm just a beginner so don't hate. This code doesn't include the function's argument. That's it.

-11 bytes thanks to Jo King

Ben

Posted 2018-08-01T15:08:21.957

Reputation: 109

I'm sorry for my naivety. I don't quite understand what you mean. – Ben – 2018-08-07T22:57:36.417

There's no indentation before the if and else, so the interpreter will throw an error. For the second part, instead of doing if x: print(True) \n else: print(false), you can just do print(x) – Jo King – 2018-08-07T23:01:21.190

But, if I print(s), the output would be the input, which is kind of useless. I can't do otherwise, unless I change the len(bin(s)[2:].replace("0","")) to be a variable, which would only output the number of 1's in the num's binary version. – Ben – 2018-08-08T17:17:56.567

I'm not saying print s, I'm saying print the condition of the if statement. In the current code that would be f%2==0. In that case you don't need any variable assignment at all, and it can be just one statement – Jo King – 2018-08-08T21:54:25.823

Okay. Now I think I understand. Thanks :) – Ben – 2018-08-09T11:41:53.233

just print the condition. No if, no assignment, snd you can move it all to one line. as it is, you won't print anything when it's false. Try having a look at the Tips for Python Golfing page or the other Python answers to this question.

– Jo King – 2018-08-09T12:22:06.430