33
\$\begingroup\$

Introduction

In number theory, a number is considered evil if there are an even number of 1's in its binary representation. In today's challenge, you will be identifying whether or not a given number is evil.

Challenge

Your job is to write a full program or function which accepts a single, non-negative integer as input and outputs (or returns) whether or not that number is evil.

  • You may output any truthy value if the number is evil, and any falsy value if the number is not evil.
  • You may input and output in any acceptable format.
  • Standard loopholes are disallowed.
  • OEIS sequence A001969 is the sequence containing all evil numbers.
  • Here is a list of the first 10000 evil numbers, for reference (and more test cases!)
  • This question is , so the shorter, the better.
  • Don't be put off by extremely short answers in golfing languages. I encourage you to submit in any language you like.
  • Here are some test cases:

    3 => True
    11 => False
    777 => True
    43 => True
    55 => False
    666 => False
    

The Leaderboard

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

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

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes

/* Configuration */

var QUESTION_ID = 169724; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 81420; // This should be the user ID of the challenge author.

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if (OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    //else console.log(body);
  });

  valid.sort(function(a, b) {
    var aB = a.size,
      bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function(a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

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

    var lang = a.language;
    lang = jQuery('<a>' + lang + '</a>').text();

    languages[lang] = languages[lang] || {
      lang: a.language,
      lang_raw: lang,
      user: a.user,
      size: a.size,
      link: a.link
    };
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function(a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i) {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
      .replace("{{NAME}}", lang.user)
      .replace("{{SIZE}}", lang.size)
      .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

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

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

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

table thead {
  font-weight: bold;
}

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

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

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

EDIT: I believe this question is not a duplicate of this, because whereas that question is asking to count the number of ones, this question is asking whether the number of ones is even. Although you can accomplish this question by simply counting the bits, there are other approaches too.

\$\endgroup\$
  • 2
    \$\begingroup\$ Related (XOR-ing every binary digit is the same as taking the sum modulo-2). \$\endgroup\$ – Kevin Cruijssen Aug 1 '18 at 15:25
  • 4
    \$\begingroup\$ Possible duplicate of Count the number of ones in an unsigned 16-bit integer \$\endgroup\$ – Beta Decay Aug 1 '18 at 17:11
  • 2
    \$\begingroup\$ @BetaDecay but that doesn't work in reverse: i.e. you cannot take all of these answers and remove the mod 2. Therefore, this challenge invites some new methods. \$\endgroup\$ – Amphibological Aug 1 '18 at 20:29
  • 13
    \$\begingroup\$ I believe that 666 => False should be a test case. \$\endgroup\$ – user2390246 Aug 2 '18 at 10:38
  • 3
    \$\begingroup\$ Leaderboard is broken for me \$\endgroup\$ – Jo King Aug 4 '18 at 2:42

86 Answers 86

1
\$\begingroup\$

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})*$

\$\endgroup\$
  • 1
    \$\begingroup\$ ^((((.*)(?=\4$))*.(.*)(?=\5$)){2})*$ is only 36 bytes. \$\endgroup\$ – Neil Feb 5 at 10:34
0
\$\begingroup\$

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!

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

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

Julia 0.6, 20 bytes

n->count_ones(n)%2<1

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\$
  • \$\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 '18 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 '18 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\$ – heather Aug 2 '18 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 '18 at 20:17
  • \$\begingroup\$ @OMᗺ fixed by switching to input() \$\endgroup\$ – heather Aug 2 '18 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\$

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.

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

><>, 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
\$\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\$
  • \$\begingroup\$ You don't need to stringify the binary \$\endgroup\$ – Jo King Aug 7 '18 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\$
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Luis felipe De jesus Munoz Aug 3 '18 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\$ – Jonathan Frech Aug 3 '18 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\$ – Amphibological Aug 4 '18 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 '18 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\$

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

\$\endgroup\$
  • \$\begingroup\$ This doesn't work without the indentation. Also you don't have to print the words truthy/falsey. You can just print the condition instead of using an if statement \$\endgroup\$ – Jo King Aug 6 '18 at 9:11
  • \$\begingroup\$ I'm sorry for my naivety. I don't quite understand what you mean. \$\endgroup\$ – Ben Aug 7 '18 at 22:57
  • \$\begingroup\$ 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) \$\endgroup\$ – Jo King Aug 7 '18 at 23:01
  • \$\begingroup\$ 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. \$\endgroup\$ – Ben Aug 8 '18 at 17:17
  • \$\begingroup\$ 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 \$\endgroup\$ – Jo King Aug 8 '18 at 21:54
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\$
  • \$\begingroup\$ Could you please add a comma after Scala in the title of your answer so it doesn't break the scoreboard? \$\endgroup\$ – Amphibological Aug 4 '18 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\$

05AB1E, 4 bytes

b1¢È

Try it online!

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

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

PowerShell, 44 bytes

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

Try it online!

Straightforward counting.

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

Brain-Flak, 76 bytes

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

Try it online!

Explanation

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

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

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.