| Bytes | Lang | Time | Link |
|---|---|---|---|
| nan | 250117T012415Z | RARE Kpo | |
| 005 | Japt | 170912T161653Z | Shaggy |
| 021 | C | 230627T101031Z | Toby Spe |
| 021 | Regex Tcl ARE | 230407T082334Z | Deadcode |
| 043 | Python | 230528T093339Z | The Empt |
| 117 | Sed | 230624T174356Z | Toby Spe |
| 002 | Thunno 2 M | 230528T133214Z | The Thon |
| 004 | Nekomata + e | 230528T021532Z | alephalp |
| 029 | PARI/GP | 230416T122750Z | 138 Aspe |
| 007 | J | 230408T034436Z | south |
| 040 | PowerShell | 230407T211537Z | James Fl |
| 004 | Vyxal g | 230407T183206Z | emirps |
| nan | 230407T085452Z | The Thon | |
| 003 | Japt ! | 230407T143723Z | noodle p |
| 011 | Regex PCRE1 | 230407T082200Z | Deadcode |
| 012 | Regex Java / Perl / PCRE / .NET | 230407T082039Z | Deadcode |
| 017 | Regex ECMAScript or better | 210328T051604Z | Deadcode |
| 005 | Pyt | 221230T114059Z | Kip the |
| 241 | PHP | 170925T103138Z | Titus |
| 011 | JavaScript | 220725T115051Z | noodle p |
| 018 | Perl 5 | 220724T070822Z | Deadcode |
| 017 | C# | 220724T182832Z | Eric Xue |
| 003 | Implicit | 170913T141217Z | MD XF |
| 033 | Python 2 | 170912T163446Z | Rod |
| 031 | C | 170913T234440Z | peterh |
| 012 | JavaScript Node.js | 170913T182129Z | Dennis |
| 012 | Cubically | 170913T141950Z | user2027 |
| 016 | QBIC | 170913T142615Z | steenber |
| 018 | C gcc | 170912T164537Z | cleblanc |
| 028 | Perl 5 | 170913T043921Z | Xcali |
| 011 | TIBasic | 170913T040128Z | Timtech |
| 010 | Julia 0.6 | 170913T030336Z | Dennis |
| 016 | Python 3 | 170912T192733Z | Dennis |
| 014 | JavaScript ES6 | 170912T214253Z | Neil |
| 016 | Kotlin | 170912T211633Z | jrtapsel |
| 003 | Jelly | 170912T192333Z | Dennis |
| 002 | MATL | 170912T185528Z | Dennis |
| 018 | Python 2 | 170912T164643Z | Erik the |
| 021 | Mathematica | 170912T162808Z | NoOneIsH |
| 005 | Pyth | 170912T165623Z | Mr. Xcod |
| 004 | MATL | 170912T170930Z | Mr. Xcod |
| 006 | Pyke | 170912T171531Z | Mr. Xcod |
| 009 | CJam | 170912T170653Z | Luis Men |
| 004 | Actually | 170912T170026Z | Erik the |
| 024 | Haskell | 170912T165719Z | jferard |
| 003 | Husk | 170912T161904Z | H.PWiz |
| 005 | Actually | 170912T165055Z | user4594 |
| 025 | Retina | 170912T164547Z | Leaky Nu |
| 002 | 05AB1E | 170912T164235Z | Erik the |
| 016 | Java OpenJDK 8 | 170912T163538Z | Roberto |
| 005 | Jelly | 170912T163805Z | DJMcMayh |
| 005 | Jelly | 170912T162543Z | Erik the |
| 003 | Neim | 170912T161942Z | Okx |
awk
jot 1024 |
awk 'function __(_) { return (2^3)^((3^3+4)*(5+6)) \
% (_ = +_) < (!!_ < _)
} __($_)'
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
11 2048
12 4096
13 8192
.
.
1021
224711641857789488466163148848628091702247122367788321
591787601447165844756876203915885596653009420026400142349839
241697073487211018020778116059288299342655472209866781081856
595377774501557617649316353690106257211047688352928078601842
391388176034046454188138355732872799934057423099645381044195
41203028017152
1022
449423283715578976932326297697256183404
494244735576643183575202894331689513752407831771193306018840
052800284699678483394146974422036041556232118576598685310944
419733562163713190755549003115235298632707380212514422095376
705856157203684782776352068092908376276711465745599868114846
19929076208839082406056034304
1023
898846567431157953864652
595394512366808988489471153286367150405788663379027504815663
542386612037680105600569399356966788293948844072083112464237
153197370621888839467124327426381511098006230470597265414760
425028844190753411712314407369565552704136185816752553422931
49119973622969239858152417678164812112068608
This function captures all positive and finite powers of 2 of the double floating-point data type.
Japt, 5 bytes
õ!²øU
Explanation
Generate an array of integers (õ) from 1 to input U. Raise 2 to the power of each (!²). Check if the array includes (ø) U.
C, 21 bytes
Requirement: 2's complement arithmetic
f(x){return!(x&x-2);}
This is a minor modification of the well-known expression x & (x-1) which yields zero when x is an power of two (including 2⁰, i.e. unity). By subtracting an additional 1 from the right-hand side, we exclude the value that has that bit set.
0 results in a true value; if we wish to exclude that, we need an extra 3 bytes: !(x&x-2)&&x.
Demo
f(x){return!(x&x-2);}
#include <stdio.h>
#include <limits.h>
int main(void)
{
for (int i = INT_MAX; i > 0; --i) {
if (f(i)) { printf("%d\n", i); }
}
}
The demo produces this output on a 32-bit system:
1073741824
536870912
268435456
134217728
67108864
33554432
16777216
8388608
4194304
2097152
1048576
524288
262144
131072
65536
32768
16384
8192
4096
2048
1024
512
256
128
64
32
16
8
4
2
Regex (Tcl ARE), 24 22 21 bytes
^((x((xx)*))\2*$)\3 - 19 bytes - Powers of 2 - Try it online!
^(x|(x((xx)*))\2*)$\3 - 21 bytes - Completely even - Try it online!
Tcl ARE has both positive and negative lookaheads, but neither backreferences nor captures can be done inside one. So seemingly, it would be impossible to match powers of 2 instead of non-powers, because all of the ECMAScript regexes use backreferences inside a lookahead. This challenge states "output a truthy value if it is completely even and a falsy value if it is not", so an inverted-logic regex, such as ^(x*)(\1\1)+$|^x$, would not satisfy the rules.
But as it so happens, in Tcl ARE it seems that any group anchored on both sides (^ at the beginning and $ at the end, either inside or outside the group as long as it's adjacent to the parentheses) in all its alternatives will be treated as atomic (preventing the engine from doing the equivalent of backtracking into that expression if the pattern fails to match at a later point) after matching the $. This does not appear to be documented, but it can be exploited to emulate a negative match. The equivalent in engines that support atomic groups would be:
^(?>(x((xx)*))\1*$)\2 - 21 bytes - Powers of 2 - Try it online!
^(?>(x\B((xx)*))\1*$)\2 - 23 bytes - Completely even - Try it online!
^(?>x$|(x((xx)*))\1*$)\2 - 24 bytes - Completely even - Try it online!
These in turn are based on the 17 byte ECMAScript regex ^(?!(x(xx)+)\1*$). The logic of the Tcl ARE version is to assert that the largest odd factor of \$n\$ is \$1\$. The "completely even" version additionally asserts than \$n\ne 1\$.
Even more strangely than the atomic grouping behavior, Tcl ARE apparently records the positions where word-boundary-match operators (\m, \M, \y, \Y) were used inside a capture group, and repeats them if that group is repeated via a backreference. So ^((x\Y((xx)*))\2*$)\3 (21 bytes) not only doesn't match \$1\$, but doesn't match \$2\$ either: Try it online!
Explanation for Powers of 2 (19 bytes):
^
( # Group an expression that is anchored to start at its
# beginning and to end at its end, thus telling the Tcl ARE
# regex engine to treat it as atomic, not backtracking into
# it if a subsequent match fails.
( # \2 = sum of the following, which will be the largest odd
# number that results in a match for what follows:
x # 1; tail -= 1
((xx)*) # \3 = any even number, including zero, trying the largest
# values first; tail -= \3
)
\2*$ # Assert that \2 divides tail; anchor to end of string
)
\3 # Now that the above match is locked in and won't backtrack,
# assert that \3 == 0, as no other value can match when
# tail == 0 (at the end of the string), thus asserting that
# \2 == 1, i.e. that the largest odd factor of N is 1.
For Completely even (21 bytes), an alternative of x$ is inserted as the first choice (but with the $ moved to the outside of the group so that it applies to both alternatives). If \$n=1\$ and this alternative matches, it effectively acts like a boolean short-circuit operator – the powers of 2 test won't be done, and \3 will not be set.
An alternative method to match powers of 2 is ^((x+?)((\2\2)*$))\3 (20 bytes): Try it online! - this uses the same atomic grouping trick, but the logic is to assert that the smallest quotient from dividing \$n\$ by any odd number is \$n\$ (thus it's implied that the only odd divisor of \$n\$ is \$1\$). For "completely even" numbers this becomes ^(x|(x+?)((\2\2)*))$\3 (23 22 bytes): Try it online! But this method is much slower than the primary one shown in this answer, and Tcl cannot even match \$n=64\$ within 60 seconds.
Python, 43 Bytes
import math
lambda x:math.log(x,2)%1or x==1
Outputs false for completely even number and outputs a truthy value for not completely even number.
Try it online (2 bytes added to allow testing)
Completely even numbers are just powers of 2 excluding 1. This programme takes the binary logarithm of the number. This only gives an integer when the argument is a power of 2. The modulo is to check if it is an integer.
Sed, 117 bytes
Not the obvious language for an arithmetic code-golf, but still fun:
:a
s/^0*2$/T/
s/.*[,0]$/F/
t
s/[13579]/&,/g
y/123456789/011223344/
s/,0/5/g
s/,1/6/g
s/,2/7/g
s/,3/8/g
s/,4/9/g
ta
ba
This works using successive division by 2, terminating when we reach 2 (true) or a value that ends in zero (which must be a multiple of 5, or zero itself) or with a carry-out from having divided an odd number.
In more detail:
:a # start of loop
s/^0*2$/T/ # reached 2
s/.*[,0]$/F/ # reached an odd number
t # in which case, jump to end
s/[13579]/&,/g # odd numbers cause a carry when divided
y/123456789/011223344/ # divide by two
s/,0/5/g # add the carry
s/,1/6/g
s/,2/7/g
s/,3/8/g
s/,4/9/g
ta # jump, clearing the "substituted" flag
ba # jump anyway
Sample input and corresponding output:
0
1
2
3
4
32
64
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
F
F
T
F
T
T
T
T
(that last value is 2¹⁰⁰⁰)
Thunno 2 M, 2 bytes
⁻ḃ
Port of Dennis's MATL answer: decrement, convert to binary, take minimum.
A plain "power of two" answer would be 4 bytes:
2BSḅ
Convert to a binary list, sum equals one?
J, 7 bytes
<[XOR<:
Uses \$n < (n \oplus n - 1)\$.
<[XOR<:
<: NB. decrement
[ NB. input
XOR NB. XOR
< NB. is n less than result
Vyxal g, 4 bytes
Kḣv₂
Can probably be golfed but it’s painful to do this on mobile.
Outputs 1 for truthy, 0 or the empty list for falsy.
K # divisors of input
ḣ # without the first element
v # vectorize the following over it
₂ # is even?
# (after which the `g` flag takes the minimum of the stack)
Thunno -, \$ 4 \log_{256}(96) \approx \$ 3.29 bytes
bdiP
Attempt This Online! or verify all test cases
Port of Dennis's MATL answer.
Thunno DD, \$ 5 \log_{256}(96) \approx \$ 4.12 bytes
1-A^<
Attempt This Online! or verify all test cases
Port of Dennis's Jelly answer.
Note: a plain "power of two" answer would be 5 chars: b1c1= (is the count of 1s in the binary representation equal to 1?)
Explanation
bdiP # Implicit input
# - flag decrements
b # Convert to a binary string
di # Get the list of digits
# This is a non-empty list of ones
# if the input is a power of two
P # Push the product of this list
# Implicit output
1-A^< # Implicit input
1- # Subtract one
A^ # Xor with input
# The highest set bit will only be conserved
# if the input is a power of two
< # Is more than input?
# Implicit output
Japt -!, 3 bytes
&-Í
This is n & -(2 - n) (simplifying to n & n-2), with the ! flag negating the result (0 becomes true, everything else becomes false)
Regex (PCRE1), 11 bytes
^(x(?1)?x|x)$ - 13 bytes - Powers of 2
^(x(?1)?x)$ - 11 bytes - Completely even
| Regex engine | Powers of 2 | Completely even |
|---|---|---|
| PCRE1 | Try it online! | Try it online! |
I'm not sure when this recursive regex was originally discovered. It was likely an accidental discovery, when someone tried to match palindromes and found that due to PCRE1's atomic subroutine calls, words consisting of only one distinct letter would only match when their length was a power of 2.
Explaining why this works is complicated, but I do intend to do it sometime.
This regex is absolutely phenomenal at being ported to this challenge; it loses 2 bytes in doing so.
Regex (Perl / PCRE), 15 bytes
^x(x(?1)?+x|x|)$ - 16 bytes - Powers of 2
^x(x(?1)?+x|x)$ - 15 bytes - Completely even
This is a port of the PCRE1 regex to engines that may have non-atomic subroutine calls.
| Regex engine | Powers of 2 | Completely even |
|---|---|---|
| Perl | Try it online! | Try it online! |
| PCRE1 | Try it online! | Try it online! |
| PCRE2 | Try it online! | Try it online! |
Regex (PCRE / Ruby), 16 bytes
^x(x\g<1>?+x|x|)$ - 17 bytes - Powers of 2
^x(x\g<1>?+x|x)$ - 16 bytes - Completely even
This is a port of the PCRE1 recursive regex to Ruby's subroutine call syntax.
| Regex engine | Powers of 2 | Completely even |
|---|---|---|
| PCRE1 | Try it online! | Try it online! |
| PCRE2 | Try it online! | Try it online! |
| Ruby | Try it online! | Try it online! |
Regex (Perl / PCRE2 / Boost / Pythonregex), 15 bytes
^x(x((?1))\2|)$ - Powers of 2
^x(x((?1)?)\2)$ - Completely even
| Regex engine | Powers of 2 | Completely even |
|---|---|---|
| Perl | Try it online! | Try it online! |
| PCRE2 | Try it online! | Try it online! |
| Boost | Try it online! | Try it online! |
Python import regex |
Try it online! | Try it online! |
I discovered this recursive regex on 2022-07-18 while working on Sum of Powers of 2. It relies on subroutine calls being atomic.
^ # tail = N = input number
x # tail -= 1
( # Define subroutine (?1)
x # match += 1; tail -= 1
((?1)) # \2 = match made by recursive call; match += \2; tail -= \2
\2 # match += \2; tail -= \2
| # or
# Match nothing, causing a cascading pop to the top level of
# recursion, ending the match.
)
$ # Assert that we've reached the end of the string.
This is similar to ^(\1\1|^x)*x$, in that the (?1) subroutine call will always return \$2^a-1\$ where \$a\$ is the depth of recursion it reached. This is why an extra \$1\$ is subtracted at the beginning (it could just as easily be done at the end, but that would be slightly slower due to backtracking).
It is very easily ported to solving this challenge; the first iteration at which it has a choice of whether to match nothing just has to be pushed down one level, at a cost of 0 bytes.
Regex (PCRE2 / Ruby), 16 bytes
^x(x(\g<1>)\2|)$ - Powers of 2
^x(x(\g<1>?)\2)$ - Completely even
| Regex engine | Powers of 2 | Completely even |
|---|---|---|
| PCRE2 | Try it online! | Try it online! |
| Ruby | Try it online! | Try it online! |
This is a port of the non-atomic recursive regex to Ruby's subroutine call syntax.
Regex (Java / Perl / PCRE / .NET), 12 bytes
^(\1\1|^x)*x$ - 13 bytes - Powers of 2
(\1\1|^x)+x$ - 12 bytes - Completely even
| Regex engine | Powers of 2 | Completely even |
|---|---|---|
| Java | Try it online! | Try it online! |
| Perl | Try it online! | Try it online! |
| PCRE | Try it online! | Try it online! |
| .NET | Try it online! | Try it online! |
Subtracts increasing powers of 2 from \$tail\$, starting with \$1\$. As such, the sum of the subtracted powers will be \$2^a-1\$ where \$a\$ is the number of iterations so far. Once the loop has matched as many iterations as it can, asserts that the remaining \$tail=1\$.
Unlike the ECMAScript regexes, this needs to do no backtracking, thus is orders of magnitude faster in standard regex engines.
As with the 17 byte ECMAScript regex, it is quite suitable for solving this challenge, as the only change necessary is upping the minimum iteration count of the loop from 0 to 1 by changing the * quantifier to a +, at a cost of 0 bytes. But an added bonus here is that the first iteration of the loop can only match at the beginning of the string, so we can remove the first ^ anchor to save 1 byte. This does make the regex much slower in most regex engines though.
Regex (Java / Perl / PCRE / Pythonregex / Ruby / .NET), 22 bytes
^((?=(\3\3|^x))(\2))*x$ - 23 bytes - Powers of 2
((?=(\3\3|^x))(\2))+x$ - 22 bytes - Completely even
| Regex engine | Powers of 2 | Completely even |
|---|---|---|
Python import regex |
Try it online! | Try it online! |
| Ruby | Try it online! | Try it online! |
This is a direct port of the 13 byte / 12 byte regex. Ruby, and Python's regex module, do not support nested backreferences, so they must be emulated via forward-declared backreferences. (Python's re module doesn't even support the latter.) The 13 byte version of this is faster than the 17 byte regexes, but golf-wise, they win.
Although this results in a fast regex that's compatible with six different engines, the recursive solutions provide the best golf for Python's regex module and Ruby.
\$\large\textit{Full programs}\$
Retina 0.8.2, 18 bytes
.+
$*
(\1\1|^.)+.$
Takes its input in decimal. Uses the Java/Perl/PCRE/.NET pure regex.
Perl 5, 24 bytes
say 1x<>~~/(\1\1|^.)+.$/
Regex (ECMAScript or better), 17 bytes
^((x+)(?=\2$))+x$ - Completely even
Takes its input in unary, as a string of x characters whose length represents the number.
Try it online! - ECMAScript
Try it online! - ECMAScript 2018
Try it online! - Java
Try it online! - Perl
Try it online! - PCRE
Try it online! - Boost
Try it online! - Python
Try it online! - Ruby
Try it online! - .NET
Remarkably, there are three completely different 17 byte solutions for Powers of 2, which blew my mind even when I thought there were two. For this challenge, only one is 17 bytes, but for plain Powers of 2 they all are.
^(?!(x(xx)+)\1*$) - 17 bytes - Powers of 2
^(?!(x(xx)+)\1*$)x - 18 bytes - Powers of 2, correct at zero
^(?!(x(xx)+)\1*$)xx - 19 bytes - Completely even
| Regex engine | Powers of 2 | Completely even |
|---|---|---|
| ECMAScript | Try it online! | Try it online! |
| Python | Try it online! | Try it online! |
| Ruby | Try it online! | Try it online! |
This is what I came up to solve a level of Regex Golf on 2014-02-21, and was also independently discovered by several others, including earlier than 2013-12-20. It's the one most similar to the well-known primality test, which is probably why most people came up with this one instead of the others.
It asserts that \$n\$ has no odd divisors of \$3\$ or greater yielding a positive quotient. It has a false positive for zero, since although zero can be divided by any odd number, the quotient is zero, not positive. This can be fixed at the cost of an extra byte: ^(?!(x(xx)+|)\1*$) or ^(?!(x(xx)+)\1*$)x.
Since the entire test is inside a (negative) lookahead, it can be adapted to answer this challenge by adding xx at the end, which enforces that only \$n≥2\$ can match.
^(?!(x*)(\1\1)+$) - 17 bytes - Powers of 2
^(?!(x*)(\1\1)+$)xx - 19 bytes - Completely even
| Regex engine | Powers of 2 | Completely even |
|---|---|---|
| ECMAScript | Try it online! | Try it online! |
| Python | Try it online! | Try it online! |
| Ruby | Try it online! | Try it online! |
This was discovered by Grimmy in 2019-02-05, without fanfare. I on the other hand was amazed, as this has no such flaw as the other negative assertion – it does not match zero.
It asserts that \$n\$ has no divisors yielding an odd quotient of \$3\$ or greater. As a negative assertion, it does not consume the power of 2 that it matches, and thus is great for use in larger regexes where it doesn't need to be wrapped in a lookahead to allow other tests to be done on the same value of \$tail\$.
The downside is that in standard regex engines, it's significantly slower than ^(?!(x(xx)+|)\1*$). In my regex engine though, they're both statically optimized into a bitwise power of 2 test unless optimizations are disabled.
^((x+)(?=\2$))*x$ - 17 bytes - Powers of 2
^((x+)(?=\2$))+x$ - 17 bytes - Completely even
| Regex engine | Powers of 2 | Completely even |
|---|---|---|
| ECMAScript | Try it online! | Try it online! |
| Python | Try it online! | Try it online! |
| Ruby | Try it online! | Try it online! |
I discovered this one in 2014-02-21, after being mentally primed by solving teukon's Dominoes 2 puzzle (which is now included in Regex Golf); teukon independently came up with it later that same day. It was the very first problem in unary that we solved by repeatedly decreasing \$tail\$ in a loop while retaining an invariant property at every step, and is probably the simplest function that is best golfed by being solved that way.
It repeatedly divides \$tail\$ by \$2\$ (asserting each time that there is no remainder) as many times as possible, and then asserts that the end result is \$1\$. This one is useful in larger regexes when it is desirable to consume the identified power of 2.
It is the most suitable for solving this challenge, “Is it a completely even number?”, as the only change necessary is upping the minimum iteration count of the loop from 0 to 1 by changing the * quantifier to a +, at a cost of 0 bytes. This enforces that \$n\$ must be evenly divided by \$2\$ at least once before yielding an end result of \$1\$.
Pyt, 5 bytes
ĐĦ1=*
Outputs 0 if not completely even, n if completely even
Đ implicit input (n); duplicate on stack
Ħ get Hamming weight
1= equal to 1?
* coerce boolean to integer and multiply by n; implicit print
PHP, 22 24+1 bytes
<?=(($n=$argn)^$n-1)>$n;
Run as pipe with -rF. Prints 1 for truthy, empty output for falsy.
hmm ... looks like a port from Dennis´ answer.
Dang, @Deadcode is right: bitwise operations rank lower than comparisons.
And try as I might, I could not find a way around the parentheses.
JavaScript, 14 11 bytes
-3 thanks to Deadcode
f=
n=>!(n&n-2)
// test numbers 0-16
const tests = [f(0), false, true, false, true, false, false, false, true, false, false, false, false, false, false, false, true]
const results = tests.map((res, n) => res === f(n))
document.write(
results.every(res => res)
? "All tests passed 😊"
: [
"Tests failed 😦",
...results.map((res, n) => !res && `f(${n}): expected ${tests[n]}`).filter(Boolean),
].join("<br />")
)
body{font-size:3rem;font-family:monospace}
Explanation - this uses this trick for checking if n is a power of 2, but uses n&n-2 instead of n&n-1 to make 1 return false
Perl 5, 20 18 bytes
say!(($_=<>)&$_-2)
Note that this would be 17 bytes with swapping allowed, but by my interpretation, the challenge specifies that swapping is not allowed.
This is modification of the classic bitwise formula for powers of 2, using \$n∧(n-2)=0\$ instead of \$n∧(n-1)=0\$. It appears nobody else has used this yet? This method would work for eliminating all powers of 2 less than any chosen power of 2. For example, to eliminate \$\{1,2,4,8\}\$, the formula would be \$n∧(n-16)=0\$.
To handle zero correctly, a port of Dennis's Jelly answer won't work, since Perl casts the result of bitwise XOR to an unsigned integer, giving the result 18446744073709551615 for 0^-1. This can be fixed with use integer, but that would result in the program being 34 bytes:
use integer;say((($_=<>)^$_-1)>$_)
There is, however, a way to have proper zero handling at 21 bytes:
say!(($_=<>)--&$_)x$_
With both zero handling and consistent truthy values, 23 bytes:
say!(($_=<>)&$_-2)>!-$_
Checking for a power of 2 is 18 bytes if returning truthy for zero is acceptable:
say!(($_=<>)&$_-1)
With proper handling of zero, it's 21 bytes:
say!(($_=<>)&$_-1)*$_
With both zero handling and consistent truthy values, 23 bytes:
say!(($_=<>)&$_-1)>!-$_
C#, 22 17 bytes
x=>x!=1&&x&x-1==0
-5 by Steffan
Implicit, 7 2 3 bytes
½?ö
Try it online! Explanation:
implicit float input
½ calculate log2(input)
? if truthy
ö push 1 if top-of-stack is whole, 0 if non-whole
implicit int output
½ pushes log2(input). If the input is 0 or 1 it will push 0.000000. 0 is a whole number so performing ö on 0 will yield 1, giving the incorrect result for the input 1. ? only performs the next command if the top of stack is truthy. So if the input was 1 or 0, it will skip the ö and print 0 as it's supposed to. Otherwise it will push 1 if log2(input) is whole and 0 if it's not.
Python 2, 33 bytes
lambda n:bin(n).count('1')==1-n%2
Recusive approach, 38 36 bytes
-2 bytes thanks to Leaky Nun
f=lambda n:n>1if n<3else f(~n%2*n/2)
C, 31 bytes
f(x){return !(x&(x-1))&&!(x-1)}
These are the powers of 2, except 1, and thus binary arithmetics solves the problem.
Cubically, 12 bytes
$R:7-8⊕7>7%6
Cubically's code is quite short and easily writable, if the solution does not involves too much (more than 1) temporary variables.
Explanation: I used other people's solutions, calculate (n^(n-1)) > n.
$ Input number n, store to memory index 7.
R Make the cube unsolved by perform a move "R" on the cube, thus the value of face 8 will be truthy (1).
:7 Set notepad value to value of memory index 7 (number n)
-8 Subtract by value of memory index 8, which is 1 because cube is unsolved.
⊕7 Calculate bit-xor of current notepad value (n-1) with value of memory index 7 (n), store to notepad.
>7 Calculate (notepad > n), store to notepad.
%6 Print value of notepad as number (0 for falsy, 1 for truthy).
QBIC, 16 bytes
[:|~2^a=b\_X1}?0
This checks all powers of 2 from 1 to the input, to see if it matches the input. Prints 1 when it does, 0 when it doesn't.
TI-Basic, 11 bytes
logBASE(Ans,2
Ans and not(fPart(Ans
Alternate solution (14 bytes):
max(Ans=2^seq(I²,I,2,Ans
Python 3, 16 bytes
lambda n:n^n-1>n
Returns True or False.
How it works
If n = 0, then n ⊕ (n - 1) = 0 ⊕ -1 = -1 < 0 = n, so the function returns False.
If n = 1, then n ⊕ (n - 1) = 1 ⊕ 0 = 1 = n, so the function returns False.
If 2k < n < 2k+1, then 2k ≤ n - 1 < 2k+1, so n and n - 1 have the 2k bit in common,
n ⊕ (n - 1) < 2k < n, and the function returns False.Finally, if n = 2k with k > 0, then n = 2k and n - 1 = 2k - 1 have no bits in common, so
n ⊕ (n - 1) = n + (n - 1) > n + 0 = n and the function returns True.
JavaScript (ES6), 14 bytes
f=
n=>n>1>(n&n-1)
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>
Python doesn't have the monopoly on chained comparisons!
Kotlin, 19 17 16 bytes
{it-1 xor it>it}
Test
private val t: (Int) -> Boolean =
{it-1 xor it>it}
fun main(args: Array<String>) {
println(t(0))
println(t(1))
println(t(999))
println(t(1024))
println(t(2))
}
Jelly, 3 bytes
^’>
How it works
^’> Main link. Argument: n
’ Decrement; yield n-1.
^ Compute the bitwise XOR of n and n-1.
This will conserve the highest set bit of n only if n is a power of two.
If n is even, n-1 will be positive and the result will be different from n.
> Test if the result is larger than n.
MATL, 2 bytes
qB
How it works
This takes advantage of MATL's convenient interpretation of truthy and falsy. q decrements the input and B gets the binary representation of the result. This yields a non-empty array of 1's (truthy) for even powers of two, an array that is either empty of contains a 0 (falsy) otherwise.
Mathematica, 21 bytes
IntegerQ@Log2@#&&#>1&
Pyth, 5 bytes
q]2{P
Alternative:
q2s{P
Explanation
q]2{P ~ Full program with implicit input (Q) at the end.
P ~ Prime factors.
{ ~ Deduplicated.
q ~ Equals?
]2 ~ The literal [2].
~ Output (implicitly).
MATL, 4 bytes
Saved a byte thanks to Luis Mendo!
Yf2=
Returns 1 (or an array of several 1s) for truthy and 0 or (the empty string) for falsy.
How?
Yf2= % Full program.
Yf % Prime factors.
2= % All equal 2?
% Output implicitly.
Pyke, 6 bytes
P}2]1q
P - Prime factors.
} - Deduplicate.
2]1 - Create a one-element list, [2].
q - Is equal?
CJam, 9 bytes
{mf2f=:*}
Anonymous block that takes the input number from the stack and replaces it by either 1 or 0.
Explanation
{ e# Begin block
mf e# Array of (repeated) prime factors
2f= e# Compare each element of that array with 2
:* e# Fold product over the array
} e# End block
Husk, 3 bytes
Returns log₂(x) if True 0 otherwise
£İ2
Explanation
£ Is it an element of the increasing sequence
İ2 powers of two (starting at 2)
Actually, 5 bytes
;R♂╙c
Explanation:
;R♂╙c
; duplicate n
R range(1, n+1)
♂╙ powers of 2
c contains n