1
\$\begingroup\$

A completely even number is a positive even integer whose divisors (not including 1) are all even.

Some completely even numbers are:

  • 2 (divisors: 2, 1)
  • 4 (divisors: 4, 2, 1)
  • 16 (divisors: 16, 8, 4, 2, 1)
  • 128 (divisors: 128, 64, 32, 16, 8, 4, 2, 1).

Some non-completely even numbers are:

  • 10 (divisors: 10, 5, 2, 1)
  • 12 (divisors: 12, 6, 4, 3, 2, 1)
  • 14 (divisors: 14, 7, 2, 1)
  • 18 (divisors: 18, 9, 6, 3, 2, 1)
  • 1, being odd, is not completely even.

0 is not completely even (it's divisible by all positive integers, including odd numbers) but you do not need to handle this.

Your challenge is to take a positive integer as input and output a truthy value if it is completely even and a falsy value if it is not. These outputs do not need to be consistent.

If your solution doesn't return a falsy value for 0, it's encouraged to show what changes would be necessary to make it do so. Especially encouraged is to show how your solution differs from checking if the input is a power of 2; in some languages it may be shorter, and in some longer.

Input may be taken via any allowed method, and output may be given via any allowed method.

The shortest code in bytes wins!

\$\endgroup\$
16
  • 1
    \$\begingroup\$ Related \$\endgroup\$
    – H.PWiz
    Sep 12, 2017 at 16:14
  • 25
    \$\begingroup\$ This is powers of 2 (credit to El'endia Starman in chat for pointing it out) \$\endgroup\$
    – Mayube
    Sep 12, 2017 at 16:22
  • 5
    \$\begingroup\$ @Xcali that one is closed, and this one doesn't have the restricted-source \$\endgroup\$
    – Stephen
    Sep 13, 2017 at 14:04
  • 3
    \$\begingroup\$ @Dennis, the question contradicts itself. By the definition given in the first paragraph, 1 is completely even, because its divisors except 1 form an empty set and so are trivially all even. \$\endgroup\$ Sep 14, 2017 at 15:30
  • 4
    \$\begingroup\$ This is still the closest thing to a pure "powers of 2" question on the whole site... and it asks you to return falsey for 1. Damnit. But this would be a good question, worthy of having positive votes, if only there were also a plain "powers of 2" question. \$\endgroup\$
    – Deadcode
    Mar 28, 2021 at 5:58

52 Answers 52

13
\$\begingroup\$

MATL, 2 bytes

qB

Try it online!

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.

\$\endgroup\$
3
  • \$\begingroup\$ Throws an error for 0. \$\endgroup\$
    – Shaggy
    Sep 12, 2017 at 19:15
  • 6
    \$\begingroup\$ Which makes the output empty and thus falsy. \$\endgroup\$
    – Dennis
    Sep 12, 2017 at 19:16
  • \$\begingroup\$ Is this an allowed output format? Why should 1 0 1 0 1 0 1 be considered falsy and not truthy? \$\endgroup\$
    – user253751
    Apr 12, 2023 at 2:30
8
\$\begingroup\$

05AB1E, 2 bytes

Óg

Try it online!

In 05AB1E only 1 is truthy. Input-1-and-input-0-verified.

\$\endgroup\$
7
\$\begingroup\$

Jelly, 3 bytes

^’>

Try it online!

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

Python 3, 16 bytes

lambda n:n^n-1>n

Returns True or False.

Try it online!

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.

\$\endgroup\$
6
\$\begingroup\$

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

\$\endgroup\$
5
\$\begingroup\$

Python 2, 18 bytes

lambda x:~-x&x<1<x

Try it online!

-3 thanks to Rod.

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

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!

\$\endgroup\$
1
  • \$\begingroup\$ This might be the first time I've ever seen JS's comparison chaining come in handy in a function this short... \$\endgroup\$ Sep 13, 2017 at 1:17
3
\$\begingroup\$

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)

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Are all positive integers truthy in Husk? \$\endgroup\$
    – Okx
    Sep 12, 2017 at 16:24
  • \$\begingroup\$ Yes, and negative integers too \$\endgroup\$
    – H.PWiz
    Sep 12, 2017 at 16:24
3
\$\begingroup\$

Japt, 6 bytes

õ!² øU

Test it


Explanation

Generate an array of integers (õ) from 1 to input U. Raise 2 to the power of each (). Check if the array includes (ø) U.

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

Python 2, 33 bytes

lambda n:bin(n).count('1')==1-n%2

Try it online!

Recusive approach, 38 36 bytes

-2 bytes thanks to Leaky Nun

f=lambda n:n>1if n<3else f(~n%2*n/2)

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ 37 bytes \$\endgroup\$
    – Leaky Nun
    Sep 12, 2017 at 16:47
  • \$\begingroup\$ 36 bytes \$\endgroup\$
    – Leaky Nun
    Sep 12, 2017 at 16:48
  • \$\begingroup\$ You have lambda n but you use variable i. \$\endgroup\$ Sep 16, 2017 at 4:41
  • \$\begingroup\$ @NoOneIsHere my bad, fixed \$\endgroup\$
    – Rod
    Sep 16, 2017 at 15:00
3
\$\begingroup\$

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.

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

Regex (Tcl ARE), 24 22 bytes

^((x((xx)*))\2*$)\3 - 19 bytes - Powers of 2 - Try it online!
^(x$|(x((xx)*))\2*$)\3 - 22 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). 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!

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! – and as a result, the 22 byte method has to be used instead.

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 (22 bytes), an alternative of x$ is inserted as the first choice. 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 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.

\$\endgroup\$
2
\$\begingroup\$

Jelly, 5 bytes

Æf=2Ȧ

Try it online!

Does NOT fail for 1!

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

Java (OpenJDK 8), 18 16 bytes

i->i>1&(i&~-i)<1

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ This also works in JS, if you replace the "skinny arrow" with a "fat arrow": tio.run/##y0osSyxOLsosKNHNy09J/… \$\endgroup\$
    – Shaggy
    Sep 12, 2017 at 19:21
  • 1
    \$\begingroup\$ Way better than the method based version, i->Integer.bitCount(i+1)==1 by 11 bytes! \$\endgroup\$
    – corsiKa
    Sep 12, 2017 at 21:53
  • \$\begingroup\$ @corsiKa The most I could golf the method based one down to was 22 bytes: i->i>1&i.bitCount(i)<2. You can call a class' static methods using an instance \$\endgroup\$ Sep 13, 2017 at 8:52
2
\$\begingroup\$

MATL, 4 bytes

Saved a byte thanks to Luis Mendo!

Yf2=

Try it here.

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.
\$\endgroup\$
2
  • \$\begingroup\$ @LuisMendo Thanks, thanks a lot! \$\endgroup\$
    – Mr. Xcoder
    Sep 12, 2017 at 17:12
  • \$\begingroup\$ @LuisMendo Thanks, addressed. \$\endgroup\$
    – Mr. Xcoder
    Sep 12, 2017 at 17:16
2
\$\begingroup\$

Pyth, 5 bytes

q]2{P

Verify all the test cases.

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).
\$\endgroup\$
2
  • \$\begingroup\$ !-PQ2 is 5 bytes too, similar idea \$\endgroup\$
    – Dave
    Sep 13, 2017 at 12:12
  • 1
    \$\begingroup\$ q2eP for 4 bytes. P gives an ordered list, so eP is the largest prime factor. \$\endgroup\$
    – hakr14
    Mar 28, 2021 at 16:14
2
\$\begingroup\$

C (gcc), 37 33 27 18 bytes

Thanks to @MD XF for the idea

f(n){n=(n^n-1)>n;}

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 20 bytes \$\endgroup\$
    – MD XF
    Sep 12, 2017 at 21:47
  • \$\begingroup\$ @MDXF Nice! I knew there was a way to determine with simple arithmetic just couldn't figure out how. \$\endgroup\$
    – cleblanc
    Sep 13, 2017 at 12:24
2
\$\begingroup\$

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

\$\endgroup\$
5
  • 1
    \$\begingroup\$ Welcome to CGCC! And, 8 bytes: n=>n&n-2. But by my interpretation OP specified that swapping truthy/falsey is not allowed, so, 11 bytes: n=>!(n&n-2) \$\endgroup\$
    – Deadcode
    Jul 25, 2022 at 17:22
  • \$\begingroup\$ Also I would recommend putting f(0) (or !f(0), if you stick with the swap) as the first element of your test array. It's disingenuous to verify that your function is returning the wrong value for zero as part of the test suite, as by the challenge's rules, it can return either truthy or falsey for an input of zero. \$\endgroup\$
    – Deadcode
    Jul 25, 2022 at 17:36
  • 1
    \$\begingroup\$ I was trying to figure out a way to skip the n==1 check but didn't think of this. Thanks! \$\endgroup\$
    – noodle man
    Jul 25, 2022 at 21:30
  • \$\begingroup\$ Another way you could save bytes, but stick with the same bitwise operation, is n=>n<2|n&n-1. This would also make it return the correct value for zero. There are two savings being done with that: using n<2 instead of n==1, and using | bitwise OR instead of || logical OR (they both work with JavaScript's operator precedence). \$\endgroup\$
    – Deadcode
    Jul 25, 2022 at 21:35
  • \$\begingroup\$ Huh, didn't know bitwise OR worked like that. I think I'll stick with your previous version though. \$\endgroup\$
    – noodle man
    Jul 25, 2022 at 21:38
2
\$\begingroup\$

Regex (Java / Perl / PCRE / .NET), 12 bytes

^(\1\1|^x)*x$ - 13 bytes - Powers of 2
(\1\1|^x)+x$ - 12 bytes - Completely even

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|^.)+.$

Try it online!

Takes its input in decimal. Uses the Java/Perl/PCRE/.NET pure regex.

Perl 5, 24 bytes

say 1x<>~~/(\1\1|^.)+.$/

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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

Vyxal g, 4 bytes

Kḣv₂

Try it Online!

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)
\$\endgroup\$
1
2
\$\begingroup\$

PowerShell, 40 bytes

param($i)(($i-band(-$i))-eq$i)-and$i-ne0

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Thunno 2 M, 2 bytes

⁻ḃ

Attempt This Online!

Port of Dennis's MATL answer: decrement, convert to binary, take minimum.


A plain "power of two" answer would be 4 bytes:

2BSḅ

Attempt This Online!

Convert to a binary list, sum equals one?

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

Neim, 3 bytes

𝐅ᛃ𝐩

Doesn't work on TIO.

\$\endgroup\$
2
  • \$\begingroup\$ Fails for input 1? \$\endgroup\$
    – Leaky Nun
    Sep 12, 2017 at 16:31
  • \$\begingroup\$ @LeakyNun Trying the program that produces the inverse output, 𝐅ᛄ𝐩 (which works on TIO), succeeds for input 1. \$\endgroup\$
    – Okx
    Sep 12, 2017 at 16:31
1
\$\begingroup\$

Jelly, 5 bytes

ÆEL’¬

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Kind of different approach :p \$\endgroup\$ Sep 12, 2017 at 16:38
1
\$\begingroup\$

Retina, 25 bytes

.+
$*
+`^(11+)\1$
$1
^11$

Try it online!

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

Actually, 5 bytes

;R♂╙c

Try it online!

Explanation:

;R♂╙c
;      duplicate n
 R     range(1, n+1)
  ♂╙   powers of 2
    c  contains n
\$\endgroup\$
1
\$\begingroup\$

Haskell, 24 bytes

f n=elem n$map(2^)[1..n]

Try it online!

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

Actually, 4 bytes

yN2=

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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