Введение
В теории чисел число считается злым, если в его двоичном представлении есть четное число единиц. В сегодняшнем испытании вы будете определять, является ли данное число злым.
Вызов
Ваша задача - написать полную программу или функцию, которая принимает одно неотрицательное целое число в качестве входных данных и выводит (или возвращает), является ли это число злым.
Таблица лидеров
Внизу страницы находится фрагмент стека, содержащий таблицу лидеров для этого вопроса. (Спасибо, @MartinEnder)
Чтобы убедиться, что ваш ответ обнаружен, начните его с заголовка, используя следующий шаблон уценки:
# Language Name, N bytes
где N
размер вашего представления. Если вы улучшите свой счет, вы можете сохранить старые результаты в заголовке, вычеркнув их. Например:
# Ruby, <s>104</s> <s>101</s> 96 bytes
Если вы хотите включить в заголовок несколько чисел (например, потому что ваш результат равен сумме двух файлов или вы хотите перечислить штрафы за флаг интерпретатора отдельно), убедитесь, что фактический результат является последним числом в заголовке:
# Perl, 43 + 2 (-p flag) = 45 bytes
Вы также можете сделать название языка ссылкой, которая затем будет отображаться во фрагменте списка лидеров:
# [><>](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>
РЕДАКТИРОВАТЬ: Я считаю, что этот вопрос не является дубликатом этого , потому что, хотя этот вопрос просит подсчитать количество единиц, этот вопрос спрашивает, является ли количество единиц четным. Хотя вы можете решить этот вопрос, просто посчитав биты, есть и другие подходы .
666 => False
должен быть контрольный пример.Ответы:
Сборка Z80 (8 бит), 2 байта
Следующий код работает только со значениями до 255:
16-битная версия (работает на всех тестовых примерах), 3 байта
Это работает со значениями до 65535.
Если вы чувствуете себя авантюрным, вы можете сбрить 1 байт, сохраняя ввод
A
иC
така затем работает
Однако это создает нагрузку на вызывающего, поэтому может быть так, что два байта (
push BC
иpop AF
) также должны быть учтены.источник
or
s are bitwise with 2 operandsor
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.P
allowed as per codegolf.meta.stackexchange.com/a/8509/29560? It's a single bit within theF
(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, sinceA
is an 8-bit register. This means it is unable to give an answer for777
, or any other unsigned value over 255.:P
A
is paired withF
, so I wouldn't acceptAB
orBA
as a 16-bit value.BC
is 16-bit, but then you need an extra instruction to load one of them intoA
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.JavaScript (ES6), 18 bytes
Try it online!
Explanation
The bitwise logic goes like this:
~-n
is 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):
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:
источник
Python 2, 25 bytes
Try it online!
bin(n)
gives a result like'0b10101'
. Reading this as a base-13 integer, we getSo
int(bin(n),13)%2
equals 1 + (number of ones inbin(n)
) modulo 2.If
n
is evil, then the result is 1; otherwise it is 0.I picked up this trick from Noodle9.
источник
lambda n:int(`n`,13)%2
. Try it online!Japt
-h!
,543 bytesTry it
Explanation
источник
¤¬x v
this is kevin's answerC# (Visual C# Interactive Compiler),
4338 bytesGolfed Try it online!
Ungolfed
Full code with tests
Releases
-5 bytes
- ReplacedCount
toSum
43 bytes
- Initial solution.Notes
источник
Bash (no external utilities),
5644 byteswhile(($1));do set $(($1/2)) $(($2+$1%2));done;!(($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 canexec
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:
For
0
:Correct result, with a bit of extra on the side.
источник
R,
3726 bytesTry it online!
An alternative to Robert S.'s answer, this eschews the built-in bit splitting
but ends up less golfyand thanks to JayCe and digEmAll ends up coming in slightly golfier.Only works for positive integers less than231−1 .
источник
%/%
and%%
operators so it would be a moot point.05AB1E, 4 bytes
Try it online or verify all test cases.
Explanation:
источник
Stax, 4 bytes
Run and debug it
источник
R,
9998443428 bytes-1 thanks to Kevin Cruijssen! -54 thanks to ngm! -10 thanks to Giuseppe! -6 thanks to JayCe!
Try it online!
Alternatively, using the
binaryLogic
package (39 bytes):источник
==0
can be<1
:)C (gcc), 36 bytes
Try it online!
Method from K&R https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
Must be compiled with optimization level 0
источник
error: expected constructor, destructor, or type conversion before '(' token
(arrow is pointing at thef
in the function name). What compiler flag(s) do I need?-O
.-O0
compiler flag.Wolfram Language (Mathematica),
2422 bytesTry it online!
источник
2∣
is an improvement onEvenQ
. Try it online!PHP,
3736 bytesTo run it:
Or Try it online!
Prints
1
for true, and0
for false.-1 byte thanks to Benoit Esnard!
источник
<?=1&~substr_count(decbin($argn),1);
. This one also prints 0 for false.Brachylog, 4 bytes
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.источник
INTERCAL,
906563 bytesTry it online!
Ungolfed and expanded (for what it's worth) with C style comments.
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 provideSEVEN 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.
источник
Attache,
1312 bytesTry it online!
(Old 13 bytes:
Even@1&`~@Bin
)This is a composition of three functions:
Bin
Sum
Even
This checks that the
Sum
of theBin
ary expansion of the input isEven
.источник
dc,
1816 bytesReturns (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.источник
Python 2, 29 bytes
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).
источник
lambda n:~bin(n).count('1')&1
replaces the modular division with something potentially less expensive.x86-16, 3 bytes
NASM listing:
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, orpopcnt eax, edi
/and al,1
(where 0 is truthy).источник
C++ (gcc) (-O0),
3631 bytesTry it online!
C++ (clang), 35 bytes
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-
andreturn
byi=
(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
источник
!=
to-
and another four by golfingreturn
toi=
.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 betweenreturn
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.SML, 32 Bytes
Explaination:
%
is function namen
is input, returns (n + %(n//2)) % 2Made by 2 bored Carnegie Mellon Students
источник
Forth (gforth), 53 bytes
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
источник
Java 8,
4036 bytes-4 bytes thanks to @Okx for something I shouldn't have forgotten myself..
Try it online.
Explanation:
Note that the character encoding for
0
and1
are48
and49
, but summing them and taking modulo-2 still holds the correct results because48%2 = 0
and49%2 = 1
.источник
n.toString(n,2)
saves 4 bytes.~n.toString(n,2).chars().sum()%2
to save one byte.0
and1
aren't truthy/falsey in Java, onlybooleans
/Booleans
are. If a challenge would state two distinct outputs are allowed the<1
could have been removed to save 2 bytes indeed. :)Perl 6, 21 bytes
Test it
Expanded:
источник
*.base(2)%9%%2
{:3(.base(2))%%2}
Retina 0.8.2, 28 bytes
Try it online! Link includes test cases. Explanation:
Convert to unary.
Partial binary conversion (leaves extra zeroes).
Delete all the zeros.
Modulo the ones by two.
Test whether the result is zero.
источник
x86 Assembly,
1211 bytes-1 byte thanks to @ceilingcat's suggestion
источник
inc eax
instead ofnot eax
. Also may want to mention that this requires a processor with support for thepopcnt
instruction.Bash + GNU utilities, 33
Try it online!
Reads input from STDIN. Outputs 1 for True and 0 for False.
dc
converts input to a binary stringtr
removes zeroswc
counts remaining ones (and trailing newline, which corrects sense of logicdc
calculates count mod 2 and outputs the answerисточник
Python 2,
2827 bytesTry it online!
Returns a truthy value if exactly one of
the ones-bit is a 1
andthe result of calling this function on n/2 is truthy
is true (orn==0
). It works becausen/2
is equivalent to a right bitshift with floor division (so Python 2 only).Alternate version, also
2827 bytesTry 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!
источник
1
and theor
to save +1 byte. Nice solution!APL (Dyalog Unicode), 10 bytesSBCS
Anonymous tacit function. Can take any array of integers as argument.
Try it online!
2∘⊥⍣¯1
convert to binary, using as many digits as needed by the largest number, separate digits along primary axis1⍪
prepend ones along the primary axis≠⌿
XOR reduction along the primary axisисточник
J, 9 bytes
Anonymous tacit function. Can take any integer array as argument.
Try it online!
1-
one minus (i.e. logical negation of)2|
the mod-2 of1#.
the sum (lit. the base-1 evaluation) of#:
the binary representationисточник
2|1+1#.#: