| Bytes | Lang | Time | Link |
|---|---|---|---|
| 039 | Python 3 | 241228T162510Z | Ben Stok |
| 030 | Raku Perl 6 rakudo | 241205T214150Z | xrs |
| 006 | Pip | 230214T202418Z | The Thon |
| 075 | Commodore BASIC V2 Commodore C64/VIC20 and C128 in 64 mode | 240104T144000Z | Shaun Be |
| 017 | Easyfuck | 240322T014459Z | Quadrupl |
| 034 | Swift | 231231T193152Z | macOSist |
| 039 | Google Sheets | 240104T153146Z | z.. |
| 003 | Vyxal 3 | 240101T123014Z | lyxal |
| 225 | Vyxal | 240101T122927Z | lyxal |
| nan | Perl 5 | 231231T223039Z | Xcali |
| 034 | Python 3 | 231229T155311Z | Larry Ba |
| 003 | Uiua | 231106T074844Z | chunes |
| 062 | Go | 231106T154306Z | bigyihsu |
| 010 | Pyth | 231105T212233Z | alt_meta |
| 003 | Nekomata + e | 230827T063818Z | alephalp |
| 004 | Thunno 2 | 230603T183028Z | The Thon |
| 007 | CJam | 230214T202028Z | emirps |
| 026 | Arturo | 230214T173633Z | chunes |
| nan | Fig | 221003T160744Z | Seggan |
| 022 | Flobnar | 220714T070814Z | Bubbler |
| 025 | Python 3.10 | 220615T162101Z | TKirishi |
| 027 | Wolfram Language Mathematica | 220615T200014Z | dirvine |
| 006 | K ngn/k | 220204T153102Z | coltim |
| 034 | Python | 220205T173451Z | Oliver |
| 024 | Swift | 220303T004103Z | Bbrk24 |
| 004 | Vyxal | 220302T120715Z | Larry Ba |
| 047 | tinylisp | 220204T154541Z | Giuseppe |
| 034 | Python 3 | 220113T203433Z | Larry Ba |
| 024 | Rust | 210713T025145Z | Ritwin |
| 003 | Vyxal | 210604T073832Z | emanresu |
| 010 | Pyth | 210712T140057Z | Michael |
| 019 | Factor | 210622T150535Z | chunes |
| 123 | MMIX | 210622T032702Z | NoLonger |
| 079 | Desmos | 201016T231837Z | Aiden Ch |
| 033 | Regex ECMAScript | 190203T070736Z | Deadcode |
| 021 | Rust | 210302T173128Z | Aiden4 |
| 070 | PowerShell | 210302T095133Z | Wasif |
| 065 | PHP 7.4 | 201017T224140Z | Zsolt Sz |
| 004 | Husk | 201017T033154Z | Razetime |
| 011 | GolfScript | 201017T023934Z | 2014MELO |
| 020 | Java JDK 10 | 180802T082016Z | Okx |
| 024 | Scala | 200810T230943Z | user |
| 008 | Arn | 200810T221402Z | ZippyMag |
| 035 | evil | 200604T112851Z | the defa |
| 013 | Golfscript | 200604T144336Z | LCU00 |
| 033 | CGCC | 200221T165713Z | qookie |
| 014 | GolfScript | 200220T211827Z | Pseudo N |
| 049 | Java | 200219T220003Z | Tom Hawt |
| 045 | chevron | 200221T004824Z | Superloa |
| 030 | Python 3 | 200219T202523Z | Dion |
| 003 | x8616 machine code | 200219T164259Z | 640KB |
| 004 | 05AB1E | 200219T152720Z | Brzyrt |
| 013 | GolfScript | 200212T203003Z | Mathgeek |
| 021 | Ruby | 180801T221139Z | akostadi |
| 053 | ink | 191016T005119Z | Sara J |
| 041 | Forth gforth | 191016T002056Z | Bubbler |
| 032 | SML | 190206T193605Z | CarManue |
| 058 | APLNARS | 190206T163224Z | user5898 |
| 034 | C# .NET Core | 190205T150359Z | dana |
| 003 | Japt h! | 180801T151835Z | Shaggy |
| 076 | BrainFlak | 190204T234119Z | MegaTom |
| 052 | PowerShell | 190130T014149Z | GMills |
| 044 | PowerShell | 190130T082121Z | mazzy |
| 004 | 05AB1E | 190130T060437Z | Jackson |
| 093 | Alchemist | 190130T041600Z | Jo King |
| 010 | CJam | 180808T115257Z | Helen |
| 012 | K oK | 181021T042925Z | Thaufeki |
| nan | Since the previous J solution by Adam is invalid for numbers having odd number of binary digits | 180802T005121Z | Bubbler |
| 014 | Gol><> | 181021T130048Z | Gegell |
| 022 | Wolfram Language Mathematica | 180801T165313Z | Jonathan |
| 004 | Pyt | 181021T034759Z | u-ndefin |
| 014 | Wolfram Language Mathematica | 181021T043029Z | Misha La |
| 010 | CJam | 180809T100223Z | lolad |
| 041 | Scala | 180804T113904Z | Kjetil S |
| 084 | Pascal FPC | 180811T152104Z | AlexRace |
| 064 | AsciiDots | 180810T193818Z | Alion |
| 031 | MATLAB | 180808T175220Z | aaaaa sa |
| 018 | JavaScript ES6 | 180801T152456Z | Arnauld |
| 063 | INTERCAL | 180802T231330Z | Ethan |
| 104 | brainfuck | 180803T104007Z | Jo King |
| 039 | Scala | 180803T135137Z | Zolt |
| 046 | Python 2 | 180805T035055Z | Joseph |
| 024 | Rust | 180804T172140Z | Noskcaj |
| 039 | perl E | 180804T012405Z | user7392 |
| 106 | EXCEL | 180802T041226Z | remoel |
| 022 | ><> | 180802T210800Z | user5828 |
| 062 | Lua 5.3.4 | 180803T004944Z | GalladeG |
| 023 | Befunge93 | 180804T030016Z | Jo King |
| 040 | Math++ | 180803T191047Z | SuperJed |
| 033 | Perl 5 | 180803T181420Z | Kjetil S |
| 044 | Bash no external utilities | 180802T205542Z | Kusalana |
| 039 | Python 3 | 180802T191933Z | auden |
| 002 | Z80 Assembly 8bit | 180801T152937Z | user8199 |
| 036 | C gcc | 180801T160216Z | vazt |
| 035 | SAS | 180802T110007Z | user3490 |
| 031 | C++ gcc O0 | 180802T121158Z | Annyo |
| 025 | MATLAB / Octave | 180801T231645Z | Wolfie |
| 003 | x8616 | 180803T060655Z | Peter Co |
| 030 | Common Lisp | 180802T184254Z | djeis |
| 025 | Python 2 | 180802T201440Z | lynn |
| 039 | Bash | 180801T215152Z | jesse_b |
| 039 | JavaScript Babel Node | 180802T141251Z | Luis fel |
| 029 | C gcc | 180802T185858Z | user5828 |
| 041 | Excel | 180801T181452Z | Eric Can |
| 027 | dc | 180802T164222Z | ბიმო |
| nan | 180802T160803Z | auhmaan | |
| 037 | Haskell | 180802T152004Z | ბიმო |
| 029 | Python 2 | 180801T170037Z | Triggern |
| 045 | C# .NET Core | 180802T090055Z | F.Carett |
| 065 | C# | 180802T141553Z | an earwi |
| 004 | Brachylog | 180802T123406Z | Sundar R |
| 036 | PHP | 180801T154845Z | Ethan |
| 020 | Julia 0.6 | 180802T120505Z | Sundar R |
| 021 | Pari/GP | 180802T100813Z | alephalp |
| 005 | Brachylog | 180802T095521Z | Fatalize |
| 057 | Red | 180802T081807Z | Galen Iv |
| 058 | C# .NET Core | 180802T075426Z | Charlie |
| 009 | J | 180801T211755Z | Adá |
| 010 | APL Dyalog Unicode | 180801T211239Z | Adá |
| 027 | Python 2 | 180801T183917Z | Jack Bro |
| 033 | Bash + GNU utilities | 180802T000629Z | Digital |
| 015 | Stacked | 180801T211926Z | Conor O& |
| 016 | dc | 180801T193739Z | Sophia L |
| 006 | Pyth | 180801T210833Z | Digital |
| 022 | Chip | 180801T201155Z | Phlarx |
| 011 | x86 Assembly | 180801T160317Z | Govind P |
| 026 | R | 180801T171058Z | Giuseppe |
| 028 | R | 180801T152448Z | Robert S |
| 028 | Retina 0.8.2 | 180801T193553Z | Neil |
| 007 | Charcoal | 180801T192601Z | Neil |
| 012 | Attache | 180801T192303Z | Conor O& |
| 081 | Yabasic | 180801T175632Z | Taylor R |
| nan | 180801T175612Z | Brad Gil | |
| 036 | Java 8 | 180801T152057Z | Kevin Cr |
| 053 | Forth gforth | 180801T173830Z | reffu |
| 004 | 05AB1E | 180801T151549Z | Kevin Cr |
| 004 | Jelly | 180801T151739Z | Erik the |
| 004 | Stax | 180801T151715Z | wastl |
Python 3, 39 Bytes
def a(n):return not bin(n).count('1')%2
Raku (Perl 6) (rakudo), 30 bytes
f($x){$x.base(2).comb('1')%%2}
AWK, 39 bytes
{for(;$1;$1=int($1/2))x+=$1%2}$0=!(x%2)
{for(;$1;$1=int($1/2)) # converting to binary
x+=$1%2} # adding digit to total
$0=!(x%2) # output evil
Pip, 8 6 bytes
%$+TBa
Outputs 0 for evil (true) and 1 for not evil (false). Prepend ! to make it the other way round.
-2 thanks to @DLosc
Explanation
%$+TBa ; Input on the command line
TBa ; Convert the input to binary
$+ ; Sum the list (count the 1s)
% ; Mod 2 (is it odd?)
; Implicit output
Commodore BASIC V2 (Commodore C64/VIC-20 and C128 in 64 mode, THEC64/THEC64 Mini, and some CBM/PET models) ~75 BASIC bytes
This listing should handle positive integers between 0 and 2147483647 inclusive, and meets all test conditions.
0 INPUTY:C=2^31:U=.
1 U=U-(Y>=C):Y=Y+(Y>=C)*C:C=C/2:ON-(C>=1)GOTO1:PRINT.=(UAND1)
Some notes: there is no error handling, nor does it check for integer-only numbers, so you may enter 3.14 and it will treat this as if you entered 3. Also, using this method, entering 0 will show -1 which in Commodore BASIC is true. I guess binary 0 has an even number of 1s in its binary representation, as zero is even, and binary 0 has zero ones.
Where you see . this is a BASIC equivalent of 0, but it is parsed faster by the interpreter.
Easyfuck, 23 19 17 bytes
Ì£î␅␏MW¼R¥␕¼×_f|µ8
due to lack of unicode representations for c1 control characters, they have been replaced by their superscripted abbreviations
Decompressed:
f(}`(>+<))"[f]>f>-'
Explanation:
f( ) declares function f
}`( ) right shifts byte at pointer and if the lost bit was a 1, it executes a lambda
>+< increments the byte to the right of the pointer
" takes in a 16 bit integer and XORs its bytes bitwise
[f]>f> runs f until the byte at the pointer is 0, then runs f once on the byte to the right
-' decrements the byte once to flip its truthiness (0->255, 1->0)
Swift, 62 55 54 53 34 bytes
let e={($0+0).nonzeroBitCount%2<1}
Nothing particularly interesting here.
Google Sheets, 39 bytes
=ISEVEN(LEN(SUBSTITUTE(BASE(A1,2),0,)))
The formula converts the number to base 2, removes all the zeros and checks if the LEN of the resulting string is even.
Perl 5, 28 + 1 = 29 bytes
Added one byte for -p as per the scoring system when the question was asked.
$_=(sprintf"%b",$_)=~y/1//%2
Outputs 0 for evil, 1 for not evil.
Go, 62 bytes
import."math/bits"
func f(n uint)bool{return OnesCount(n)%2<1}
Uses the bits.OnesCount builtin.
Pyth, 10 bytes
!%/jQ2 1 2
assign('Q',eval_input())
imp_print(Pnot(mod(div(join(Q,2),(1)),(2))))
Simply converts a given input to binary as a list, and prints the logical not of the modulo 2 for the amount of 1's in that list.
Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes
OSb
Outputs using inverted truthiness (0 -> true, 1 -> false) because of a bug with E.
OSb
b # To binary
S # Sum
O # Is odd?
Flobnar, 22 bytes
> +
|\<:
:&%!@
/<2
2 :
<
%!@ Output 1 if the result of `<` is divisible by 2, 0 otherwise...
2
\ Recursive call:
:& set current value to input value, or
/< the previous value divided by 2
2
:
> +
:| < If the current value is 0, return current (0);
: otherwise add the current value to the result of recursive call
Python 3.10, 25 bytes
lambda x:~x.bit_count()%2
It's the same number of char that Lynn's answer but with a totally "new idea".
The .bit_count() is new in Python 3.10 and returns the number of 1.
So with that, you can make it 25 bytes.
Note: I can't put a "Try It Online" because their version of Python is 3.7.8
But thank's to @pxeger's comment:
You can test the code here
Wolfram Language (Mathematica), 27 bytes
This is my first ever post on code golf, and I am doing this mostly to hone my Mathematica skills. Any suggestions are greatly appreciated!
2∣Tr[IntegerDigits[#,2]]&
This works by checking the parity of the base-2 digit sum (also called the digital sum). The method is slightly different than the other Mathematica answers.
Edit: I was able to save three bytes by changing Total -> Tr. This was found in the tips page suggested in the comments.
K (ngn/k), 6 bytes
1=/~2\
~2\convert input to base-2 representation, andnotit (flip0s and1s)1=/do an equals-reduce seeded with1; returns1if there are an odd number of 1's in the inverted base-2 representation and0if there are an even number(or none at all)
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)
Swift, 24 bytes
{$0.nonzeroBitCount%2<1}
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.
tinylisp, 47 bytes
(load library)
(d E(q((N)(even?(sum(to-base 2 N
Straightforward solution, thanks to useful library functions.
Rust, 24 bytes
|x:u8|x.count_ones()&1<1
Note that this only works for 8-bit numbers. The following works for 64-bit (but is an extra character):
|x:u64|x.count_ones()&1<1
Testing code:
fn main() {
let f = |x:u64|x.count_ones()&1<1;
const TESTS: [(u64, bool); 6] = [
(3, true),
(11, false),
(777, true),
(43, true),
(55, false),
(666, false)
];
for (x, b) in TESTS {
assert_eq!(f(x), b);
}
}
Pyth, 10 bytes
!%/.BQ"1"2
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
MMIX, 12 bytes (3 instrs)
00000000: db000000 7f000001 f8010000 ṃ¡¡¡¶¡¡¢ẏ¢¡¡
isevil SADD $0,$0,0
ZSEV $0,$0,1
POP 1,0
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\}
Regex (ECMAScript), 37 33 bytes
-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})*$
Takes its input in unary, as a string of x characters whose length represents the number.
^
(
# 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.
Regex (Perl / Java / PCRE / Python / Ruby), 26 bytes
^((((x*)(?=\4$))*+x){2})*$
Try it online! - Perl
Try it online! - Java
Try it online! - PCRE
Try it online! - Python import regex
Try it online! - Ruby
^
(
# 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*)(?=\4$))*+
x # Subtract a 1 bit
){2}
)* # Loop as many times as possible...
$ # and only match if the final result is 0.
Regex (.NET), 29 bytes
^(((?>((x*)(?=\4$))*)x){2})*$
Rust, 21 bytes
|n|n.count_ones()%2<1
Nothing fancy going on here, just counting the ones of the input then checking if it is even.
PowerShell, 70 bytes
if(([convert]::tostring($args[0],2)-replace"0","").length%2){0}else{1}
Sorry don't know if any powershell solution is posted, if so, I am ready to delete my submission.
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);
Ungolfed
echo array_reduce(
str_split(decbin($n)),
function ($c,$i) {
return $i xor $c;
},
1);
GolfScript, 11 bytes
~2base{^}*!
~2base # Convert to binary
{^}* # Xor all the numbers in the array
! # Negate the output
Arn, 8 bytes
›1¢|▬║~Ô
Explained
Unpacked: !(+\(:_b%2
! Boolean not
( Expression
+\ Fold with addition
( Expression
:_ Format implicit variable _ (initialized as stdin)...
b ... to binary
%2 Modulo 2
) Implicit, can be removed
) Implicit, can be removed
evil, 48 42 40 39 36 35 bytes
golf 1: flipping many ms to js and js to ms saved quite a bit of marking mode changes
golf 2: do..while -> repeat..until
golf 3: tbxb -> sxb - can be seen to be the same, but less intuitive
golf 4: the vzv in vtfvzv turned out to be renundant, because the accumulator already zero at that point
golf 5: aayuoy -> aluoy and tbuw -> tbaw, now outputs 0x02 for evil and 0x00 for normal
I can confirm that this language is absolutely evil. Even though it is more powerful than e.g. brainfuck, it feels worse.
Inputs via char code, outputs via char code (0x02 = evil, 0x00 = normal). This would be slightly (probably by 1 byte) shorter if the output values could be merely consistent and not necessarily falsy and truthy.
Uses a trick: to count set bits, the code adds elements to the wheel, a circular list, and then calculates the list size's parity by setting the first one to 1, the second one to 2 and traversing the list 2 steps at a time until a non-zero element is found.
rvmvtfxjxutctbuvavsxbmaluoymiiptbaw
Here's an explained version (I do not expect anybody to understand the monstrosity above, but the explanation is in a spoiler so that you can try) (I was also writing the code immediately with these comments):
COMMENTS ARE UPPERCASE, CODE IS LOWERCASE r READ INPUT AS CHAR CODE NOW DECREASE AND CHECK PARITY, WHILE ALSO COMPUTING N/2 IN THE FIRST PENTAL CELL v STORE TO FIRST PENTAL CELL m BEGINNING OF OUTER LOOP vtf IF ZERO, DONE NOW THE ACCUMULATOR HAS THE CORRECT VALUE AND THE PENTAL CELL IS ZERO, JUST LIKE IT SHOULD BE. x SET MARKING MODE INITIALLY j BEGINNING OF INNER LOOP x UNSET MARKING MODE AGAIN u FIRST DECREMENT IF ZERO (ODD), INCREASE BIT COUNTER AND PROCEED TO NEXT ITERATION tc THIS LANGUAGE SEEMS COMPARABLE TO MALBOLGE. THIS ADDS A NEW CELL TO THE WHEEL, A RESIZABLE CIRCULAR LIST. I USE IT AS THE BIT COUNTER tb GO TO NEXT ITERATION OF OUTER LOOP ODD CASE HANDLED. EVEN CASE IS (MUCH) SIMPLER u SECOND DECREMENT vav INCREMENT FIRST PENTAL CELL sxb IF ZERO, GO TO THE NEXT ITERATION OF THE OUTER LOOP; ELSE GO TO THE NEXT ITERATION OF THE INNER LOOP; EQUIVALENT TO TBXB. m END OF OUTER LOOP DO SORCERY TO COUNT WHEEL CELLS. al SET FIRST WHEEL CELL TO 1 (AND RESET THE ACCUMULATOR BACK TO 0 BY SWAPPING) uoy SET SECOND CELL TO -1 NOW IN A LOOP CHECK WHETHER 1 OR 2 GOES FIRST AND OUTPUT THE CORRESPONDING NUMBER m BEGINNING OF THE LOOP ii GO RIGHT TWICE p READ WHEEL tb IF STILL ZERO, GO BACK NOW THE NON-ZERO ELEMENT WAS FOUND a INCREMENT SO THAT VALUES ARE ACTUALLY FALSY AND TRUTHY. IF THAT REQUIREMENT WASN'T THERE, THE CODE COULD BE REDUCED SLIGHTLY (AT LEAST BY REMOVING THIS BYTE) w PRINT
Now, the most evil part. This code does not work with the normal interpreter, because it has a bug. The bug is that the command to add a cell to the wheel quite literally doesn't add a cell to the wheel (to be specific, it's missing wheelSize++;). I assume that the bug is obvious enough for me to avoid accusations of adding new built-ins to the language.
You can Try it online! using my fixed interpreter.
Golfscript, 13 bytes
~2base{},,2%!
~: turn input string into an integer
2base: turn top of stack into base two (represented by an array of 1s and 0s)
{},: filter out all 0s; the , command consumes the array and a code block ({}) and pushes an array containing only the elements for which the codeblock evaluates positivly (the 1s)
,: the top of stack is an array, so , consumes the array and pushes the length of the array
2%!: push 2, get the modulus(%) of the length and 2, and invert(!) the result
when the program halts, the stack is dumped into stdout, this results in either 1 for true or 0 for false
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.
GolfScript, 14 bytes
2base{^}*!
Explanation:
2base convert input to binary
{^}* xor all bits
! flip answer
Java, 29 28 26 64 63 49bytes
static boolean c(int r){return r==0||c(r*2)^r<0;}
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).
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
:0for falsy and:1for truthy.online interpreter defaults to printing the input at prompts, uncheck "print inp" to disable.
replace
:with^__for no prompt.
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:
DANG IT, I should have looked at the other answers first... @PeterCordes submitted this in 2018...
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
GolfScript, 13 bytes
2 base{+}*2%!
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%
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!
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.
Forth (gforth), 41 bytes
: f 1 swap 63 for 0 d2* m+ next + 2 mod ;
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
;
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
nis input, returns (n + %(n//2)) % 2
Made by 2 bored Carnegie Mellon Students
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
C# (.NET Core), 34 bytes
bool f(int i)=>i<1||i%2<1==f(i/2);
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.
Japt -h!, 5 4 3 bytes
¤å^
Explanation
¤ :Convert to base-2 string
å^ :Cumulatively reduce by XORing
:Implicitly output the last element negated
Brain-Flak, 76 bytes
{({<([()]{})>{(<([()]{})>)()}{}}<(()[[]]{}){<>([(){}])(<><{}>)}{}>)}<>({}())
Explanation
{
({ Divide by two
<([()]{})>
{(<([()]{})>)()}{}
}
# Invert other side if 1 is the next digit
<(()[[]]{}){<>([(){}])(<><{}>)}{}>)
}
<>({}()) # Process output
PowerShell, 55 52 bytes
-3 bytes thanks to @mazzy
1-([Convert]::ToString("$args",2)-replace0).Length%2
Takes input as an integer from a command-line parameter.
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
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
CJam, 16 14 11 10 bytes
Can't believe there's no CJam/GolfScript answer yet.
qi2b1e=1&!
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.
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-~:/&#:
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&#:
Gol><>, 14 bytes
IW2SD@+$|~2%zh
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
Wolfram Language (Mathematica), 24 22 bytes
- Saved two bytes thanks to Misha Lavrov.
2∣DigitCount[#,2,1]&
Pyt, 5 4 bytes
Ħ⁺2%
Explanation:
Implicit input
Ħ Convert into binary and count the 1s
⁺ Increment
2% Mod 2
Wolfram Language (Mathematica), 14 bytes
ThueMorse@#<1&
The Nth element of the Thue-Morse sequence is 1 if the number of binary digits in N is odd, and 0 otherwise.
CJam, 15 10 bytes
qi2b1e=2%!
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
Scala, 43 41 bytes
def e(n:Int):Int=if(n>0)n%2^e(n/2)else 1
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.
No conversion to binary :(
AsciiDots, 86 64 bytes
/{&}\
|(*)?#-.
*{>}:@1({+}*@:-{%}$#&
*{+}\#1/.^-/.-#2/
\-*.<#1)
Returns 1 if the number is evil, otherwise 0. Try it online!
MATLAB 31 bytes
Anonymous function, use as f=@(n)...;f(3)
@(n)1-mod(sum(dec2bin(n)-48),2)
JavaScript (ES6), 18 bytes
f=n=>n?!f(n&~-n):1
Explanation
The bitwise logic goes like this:
- For integers,
~-nis equivalent to-(-n)-1, so that just another way of doingn-1. In that particular case, we could actually have usedn-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
INTERCAL, 90 65 63 bytes
DOWRITEIN:1
DO:2<-'#0$#65535'~?':1~:1'
DOREADOUT:2
PLEASEGIVEUP
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
brainfuck, 104 bytes
+>,[++++>-[<->-----],]<[[-[[<]<]++++++++++<]<<[<,+<]++[->>]>,>[<<]>[>]<]<<<+[<[-<<+>>]<]<+[[<]++[->]<]<.
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.
Scala, 39 bytes
readInt.toBinaryString.count('1'==)%2<1
This can be run in a Scala console, after which the user has to input the integer and press enter.
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
perl -E, 39 bytes
say!((unpack"b*",pack I,pop)=~y/1/1/%2)
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,)))
><>, 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
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
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).
Befunge-93, 23 bytes
:_v#:/
v#:\+<_
_2%.@
Outputs 1 for non-evil, 0 for evil numbers. Calculates the parity of the sum of n divided by 2 repeatedly.
Math++, 40 bytes
?>a
3+3*!a>$
b+a%2>b
_(a/2)>a
2>$
!(b%2)
Perl 5, 33 bytes
sub e{pop=~//;$'?$'%2!=e($'/2):1}
Different approach, one byte longer:
sub e{(grep$_[0]&2**$_,0..31)%2^1}
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.
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.
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.
C (gcc), 36 bytes
c;f(n){for(c=0;n;c++)n&=n-1;n=~c&1;}
Method from K&R https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
Must be compiled with optimization level 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.
C++ (gcc) (-O0), 36 31 bytes
int f(int i){i=!i||i%2-f(i/2);}
C++ (clang), 35 bytes
int f(int i){return!i||i%2-f(i/2);}
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
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').
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).
Python 2, 25 bytes
lambda n:int(bin(n),13)%2
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.
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).
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
dc, 27 bytes
0sb[2~lb+sbd1<a]dsaxlb1++2%
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%
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
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- ReplacedCounttoSum - v1.0 -
43 bytes- Initial solution.
Notes
- None
Python 2, 29 bytes
lambda n:~bin(n).count('1')&1
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).
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;}
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;};
Brachylog, 4 bytes
ḃo-0
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.
PHP, 37 36 bytes
<?=1&~substr_count(decbin($argn),1);
To run it:
echo '<input>' | php -nF <filename>
Prints 1 for true, and 0 for false.
-1 byte thanks to Benoit Esnard!
Brachylog, 5 bytes
ḃ+%₂0
Explanation
ḃ Take the binary representation of the input
+ Sum the digits
%₂0 This sum modulo 2 is 0
C# (.NET Core), 58 bytes
n=>System.Convert.ToString(n,2).Replace("0","").Length%2<1
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.
J, 9 bytes
Anonymous tacit function. Can take any integer array as argument.
1-2|1#.#:
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
APL (Dyalog Unicode), 10 bytesSBCS
Anonymous tacit function. Can take any array of integers as argument.
≠⌿1⍪2∘⊥⍣¯1
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
Python 2, 28 27 bytes
f=lambda n:n<1or n&1^f(n/2)
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
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!
Bash + GNU utilities, 33
dc -e2o?p|tr -d 0|wc -c|dc -e?2%p
Reads input from STDIN. Outputs 1 for True and 0 for False.
dcconverts input to a binary stringtrremoves zeroswccounts remaining ones (and trailing newline, which corrects sense of logicdccalculates count mod 2 and outputs the answer
Stacked, 15 bytes
[bits sum 2%0=]
Checks whether or not the sum of the bits of the input mod 2 (2%) is 0 (0=).
dc, 18 16 bytes
[2~rd1<M+]dsMx2%
Returns (to the stack) 0 for evil and 1 for not evil
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.
Pyth, 6
!xFjQ2
Explanation
jQ2 # Convert input to base 2 list
xF # reduce on XOR
! # logical negation
Chip, 22 bytes
ABCDEFGHe
a{{{{{{{{*f
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.
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
R, 37 26 bytes
!sum(scan()%/%2^(0:31))%%2
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\$.
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
Alternatively, using the binaryLogic package (39 bytes):
!sum(binaryLogic::as.binary(scan()))%%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.
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
Attache, 13 12 bytes
Even@Sum@Bin
(Old 13 bytes: Even@1&`~@Bin)
This is a composition of three functions:
BinSumEven
This checks that the Sum of the Binary expansion of the input is Even.
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
Perl 6, 21 bytes
*.base(2).comb(~1)%%2
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?
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..
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.
Forth (gforth), 53 bytes
: f 1 swap begin 2 /mod -rot xor swap ?dup 0= until ;
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
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

