52
\$\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\$
24
  • 2
    \$\begingroup\$ Related (XOR-ing every binary digit is the same as taking the sum modulo-2). \$\endgroup\$ 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
    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\$ Aug 1, 2018 at 20:29
  • 21
    \$\begingroup\$ I believe that 666 => False should be a test case. \$\endgroup\$ Aug 2, 2018 at 10:38
  • 2
    \$\begingroup\$ Yes, 666 is not evil, but 616 is. More evidence corroborating Papyrus 115! \$\endgroup\$
    – aschepler
    Aug 7, 2018 at 11:41

123 Answers 123

1
\$\begingroup\$

Rust, 21 bytes

|n|n.count_ones()%2<1

Try it online!

Nothing fancy going on here, just counting the ones of the input then checking if it is even.

\$\endgroup\$
1
\$\begingroup\$

Desmos, 251 201 197 178 79 bytes

Wow... Coming back to this after months, and finding the most obvious golfs... lol

a=[0,...floor(\log_2N)]
f(N)=\{\mod(\total(\floor(\mod(N,2^a2)/2^a)),2)=0:1,0\}

Try It On Desmos!

Try It On Desmos! - Prettified

\$\endgroup\$
2
  • \$\begingroup\$ u dont need the comma before ... \$\endgroup\$
    – naffetS
    May 6, 2022 at 3:37
  • \$\begingroup\$ and u can call \total with dot notation \$\endgroup\$
    – naffetS
    May 6, 2022 at 3:39
1
\$\begingroup\$

MMIX, 12 bytes (3 instrs)

00000000: db000000 7f000001 f8010000           ṃ¡¡¡¶¡¡¢ẏ¢¡¡
isevil  SADD $0,$0,0
        ZSEV $0,$0,1
        POP  1,0
\$\endgroup\$
1
\$\begingroup\$

Factor, 19 bytes

[ bit-count even? ]

Try it online!

Should be self-explanatory, I hope.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ tfw not a native english speaker \$\endgroup\$
    – Razetime
    Jun 22, 2021 at 15:25
1
\$\begingroup\$

Pyth, 10 bytes

!%/.BQ"1"2

Try it online!

Trying to learn Pyth, so this is my go at it. How it works:

Convert the input to binary, count the number of "1"s, check whether they're even, invert the output (so it checks whether they're odd. In more detail:

!                 # negate output (0 -> 1, 1 -> 0)
    %             # check whether the following block returns an even number
        /         # count string occurences in...
            .B    # ...the binary string version of...
                Q # ...the input
            "1"   # the string 1; the string to be count the occurences of
    2             # the 2 used by the modulo parity check
\$\endgroup\$
1
\$\begingroup\$

Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes

OSb

Try it online!

Outputs using inverted truthiness (0 -> true, 1 -> false) because of a bug with E.

OSb
  b # To binary
 S  # Sum
O   # Is odd?
\$\endgroup\$
0
\$\begingroup\$

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

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

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.

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

Red, 57 bytes

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

Try it online!

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

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

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.

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

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!

\$\endgroup\$
6
  • \$\begingroup\$ 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). \$\endgroup\$ Aug 2, 2018 at 19:25
  • \$\begingroup\$ 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 \$\endgroup\$ Aug 2, 2018 at 19:31
  • \$\begingroup\$ @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 =) \$\endgroup\$ Aug 2, 2018 at 19:56
  • \$\begingroup\$ I won't - there are already shorter ones, but your submission still uses a preassigned variable as input which is not allowed. \$\endgroup\$ Aug 2, 2018 at 20:17
  • \$\begingroup\$ @OMᗺ fixed by switching to input() \$\endgroup\$ Aug 2, 2018 at 20:24
0
\$\begingroup\$

Math++, 40 bytes

?>a
3+3*!a>$
b+a%2>b
_(a/2)>a
2>$
!(b%2)
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ You don't need to stringify the binary \$\endgroup\$
    – Jo King
    Aug 7, 2018 at 23:03
0
\$\begingroup\$

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.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ Aug 3, 2018 at 13:56
  • 1
    \$\begingroup\$ This submission seems to be a snippet which is disallowed. Please change your submission to either a full program or a function definition. \$\endgroup\$ Aug 3, 2018 at 14:04
  • \$\begingroup\$ Also, could you please make the title of your answer into a header (i.e. # Scala, 34 bytes) to fix the scoreboard? \$\endgroup\$ Aug 4, 2018 at 15:43
  • \$\begingroup\$ @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 \$\endgroup\$
    – Zoltán
    Aug 6, 2018 at 7:56
0
\$\begingroup\$

MATLAB 31 bytes

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

@(n)1-mod(sum(dec2bin(n)-48),2)
\$\endgroup\$
0
\$\begingroup\$

AsciiDots, 86 64 bytes

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

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

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

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 :(

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

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

\$\endgroup\$
1
  • \$\begingroup\$ Could you please add a comma after Scala in the title of your answer so it doesn't break the scoreboard? \$\endgroup\$ Aug 4, 2018 at 15:38
0
\$\begingroup\$

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

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

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.

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

GolfScript, 14 bytes

2base{^}*!

Try it online!

Explanation:

2base         convert input to binary
     {^}*     xor all bits
         !    flip answer
\$\endgroup\$
1
  • \$\begingroup\$ This appears to be only 10 bytes \$\endgroup\$
    – Jo King
    Jul 31, 2022 at 1:40
0
\$\begingroup\$

GolfScript, 11 bytes

~2base{^}*!

Try it online!

~2base        # Convert to binary
      {^}*    # Xor all the numbers in the array
          !   # Negate the output
\$\endgroup\$
0
\$\begingroup\$

PHP 7.4, 65 bytes

Input is given in $n

echo array_reduce(str_split(decbin($n)),fn($c,$i) => $i xor$c,1);    

or prior to PHP 7.4: 76 bytes

echo array_reduce(str_split(decbin($n)),function($c,$i){return$i xor$c;},1);

Try it online

Ungolfed

echo array_reduce(
    str_split(decbin($n)),
    function ($c,$i) {
        return $i xor $c;
    },
1);
\$\endgroup\$
0
\$\begingroup\$

PowerShell, 70 bytes

if(([convert]::tostring($args[0],2)-replace"0","").length%2){0}else{1}

Try it online!

Sorry don't know if any powershell solution is posted, if so, I am ready to delete my submission.

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

Vyxal, 10 3 bytes

b∑₂

Try it Online!

b∑  # Sum of binary digits
  ₂ # Is even?
\$\endgroup\$
1
0
\$\begingroup\$

Python 3, 34 bytes

lambda n:not f"{n:b}".count("1")&1

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ You can do lambda x:~x.bit_count()%2 \$\endgroup\$
    – TKirishima
    May 12, 2022 at 22:20
0
\$\begingroup\$

Swift, 24 bytes

{$0.nonzeroBitCount%2<1}

Try it online

Type information not included, since the argument can be any FixedWidthInteger. For example, all of the following are valid:

let f: (Int) -> Bool = {$0.nonzeroBitCount%2<1}
let g: (UInt64) -> Bool = {$0.nonzeroBitCount%2<1}
let h: (CChar) -> Bool = {$0.nonzeroBitCount%2<1}

Unlike many other C-family languages, integers cannot implicitly be converted into booleans, and characters cannot be implicitly converted to numbers, so the approaches taken by the top C++ and C# answers are too verbose.

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

Python, 34 bytes

lambda x:not bin(x).count('1')%2

Converts input to bin, then counts 1s, mod 2 (invert because of even=1)

Try it online (Python 3.8.0b4)

Try it online (OLD) (Python 3.8.0b4)

\$\endgroup\$
2
  • \$\begingroup\$ This looks like a snippet which just evaluates to the answer, which isn't one of our allowed output methods. You'd need to include print() around the expression in your answer, or convert your answer to a function, like lambda x:not bin(x).count('1')%2 \$\endgroup\$
    – pxeger
    Mar 8, 2022 at 7:50
  • \$\begingroup\$ You can do lambda x:~x.bit_count()%2 \$\endgroup\$
    – TKirishima
    May 12, 2022 at 22:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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