title: Is this number an integer power of -2?

text:
# Question
Title: Is this number an integer power of -2?
There are clever ways of determining whether a number is a power of 2. That's no longer an interesting problem, so let's determine whether a given integer is an integer power of **-2**. For example:

```
-2 => yes: (-2)¹
-1 => no
0 => no
1 => yes: (-2)⁰
2 => no
3 => no
4 => yes: (-2)²

```

## Rules

* You may write a program or a function and use any of the standard methods of receiving input and providing output.
* Your input is a single integer, and output must be a truthy value if the integer is an integer power of -2, and a falsy value otherwise. No other output (e.g. warning messages) is permitted.
* The usual integer overflow rules apply: your solution must be able to work for arbitrarily large integers in a hypothetical (or perhaps real) version of your language in which all integers are unbounded by default, but if your program fails in practice due to the implementation not supporting integers that large, that doesn't invalidate the solution.
* You may use any programming language, but note that these loopholes are forbidden by default.

## Winning condition

This is a contest: the answer which has the fewest bytes (in your chosen encoding) is the winner.

# Answer
> 29 votes
## Mathematica, 22 bytes

```
EvenQ@Log2@Max[#,-2#]&

```

Try it online! (Using Mathics instead, where this solution also works.)

I tried to find a solution with bitwise operators for a while, and while one definitely exists, I ended up finding something which is probably simpler:

* `Max[#,-2#]` multiplies the input by **-2** if it's negative. Multiplying by another factor of **-2** doesn't change whether the value is a power of **-2** or not. But now all odd powers of **-2** have been turned into even powers of **-2**.
* But even powers of **-2** are also even powers of **2**, so we can use a simple `Log2@...` and check if the result is an integer (to check whether it's a power of **2**). This already saves two bytes over `Log[4,...]` (another way to look at even powers of **-2**).
* As an added bonus, checking whether a value is an even integer is shorter than just checking whether it's an integer: we can save three more bytes by using `EvenQ` instead of `IntegerQ`.

# Answer
> 19 votes
# Jelly, 5 bytes

```
æḟ-2=

```

Try it online!

### How it works

```
æḟ-2=  Main link. Argument: n

æḟ-2   Round n towards 0 to the nearest power of -2.
    =  Test if the result is equal to n.

```

# Answer
> 14 votes
# Jelly, 6 bytes

```
b-2S⁼1

```

Try it online!

This is based on how Jelly converts an integer *N* to any arbitrary base *B*, doing so by converting *N* to an array, in which each integer is a digit *d* of (*N*)*B*, which can have a value 0≤*Vd*\<*B*. Here, we will 0-index digits from the right, so every digit adds *VdBd* to form *N*. *Vd*\<*B**VdBd*\<*BBd*=*B**d*+1, therefore every possible *N* has only one unique representation, if we ignore leading 0s in (*N*)*B*.

Here, *d*=input, *B*=-2. *N*=*Bd*=1*Bd*=*VdBd*⇔1=*Vd**Vd*=1, and, since we're not adding any other multiples of powers of *B*, every other *V* would be 0. Right now, the array should be a 1 concatenated with *d* 0s. Since Jelly 1-indexes from the left, we should check whether the array's 1st element is 1, and all other elements are 0.

Hmm... all good, right? No? What's going on? Oh yeah, I have a better idea! First, let's take the sum of all of the integers in the array, treating it as if it was an integer array and not a number in base -2. If it is 1, it means that there is only one 1, and all other integers are 0. Since there can't be leading zeroes, except in the case of 0-2 (where the sum would be 0≠1 anyways), the 1st integer must be non-zero. The only non-zero integer in the array is the 1, so it must be the first one. Therefore, this is the only case that the sum of all of the integers in the array would be 1, because the smallest possible sum of a pair of positive integers is Σ{1,1}=2, since the smallest positive integer is 1. Every integer in a base representation is non-negative, so the only way the sum is 1 is to only have one 1, and all other integers are 0. Therefore, we can just check if the sum of all of the integers in the array is 1.

Here is what the code does:

```
b-2S⁼1 Main link. Arguments: d
b-2    Convert d to base -2.
   S   Take the sum.
    ⁼1 Check if the sum is equal to 1.

```

# Answer
> 13 votes
# Python, 46 bytes

*-2 bytes thanks to @ovs.*

```
def g(x):
 while x%-2==0!=x:x/=-2
 return x==1

```

Function with usage:

```
g(4) # put your number between the brackets

```

Try it online!

# Answer
> 12 votes
# Python 2, ~~98~~ 50 bytes

```
lambda x:x*(x&-x==abs(x))*((x<0)^x.bit_length()&1)

```

Try it online!

# Answer
> 12 votes
# JavaScript (ES6), 37 28 24 bytes

```
f=x=>!x|x%2?x==1:f(x/-2)

```

Saved 4 bytes thanks to Arnauld.

```
f=x=>!x|x%2?x==1:f(x/-2)

console.log(f(-2));
console.log(f(-1));
console.log(f(0));
console.log(f(1));
console.log(f(2));
console.log(f(3));
console.log(f(4));
```

# Answer
> 12 votes
# Python 2, ~~35~~ ~~34~~ 32 bytes

```
f=lambda n:n==1or n!=n%2<f(n/-2)

```

Try it online!

# Answer
> 12 votes
# 05AB1E, 8 bytes

```
Y(IÄÝm¹å

```

Try it online! or as a Test suite

**Explanation**

```
Y(         # push -2
  IÄÝ      # push range [0 ... abs(input)]
     m     # element-wise power
      ¹å   # check if input is in the resulting list

```

# Answer
> 10 votes
# Excel, ~~40~~ 36 bytes

Saved 4 bytes by CallumDA

Excel can certainly do it but correcting errors adds 11 bytes

```
=IFERROR(-2^IMREAL(IMLOG2(A1)),1)=A1

```

Input is in cell `A1`. Output is `TRUE` or `FALSE`

If it was allowed to return either `FALSE` or `#NUM!` error for false values, it would be only 25 bytes:

```
=-2^IMREAL(IMLOG2(A1))=A1

```

# Answer
> 9 votes
# C (gcc), ~~34~~ 29 bytes

```
f(n){n=n%2?n==1:f(n?n/-2:2);}

```

Try it online!

# Answer
> 8 votes
# MATL, ~~9~~ 8 bytes

```
2_y|:q^m

```

Try it online! Or verify all test cases.

### How it works

Consider input `-8` as an example

```
2_    % Push -2
      % STACK: -2
y     % Implicit input. Duplicate from below
      % STACK: -8, -2, -8
|     % Absolute value
      % STACK: -8, -2, 8
:     % Range
      % STACK: -8, -2, [1 2 3 4 5 6 7 8]
q     % Subtract 1, element-wise
      % STACK: -8, -2, [0 1 2 3 4 5 6 7]
^     % Power, element-wise
      % STACK: -8, [1 -2 4 -8 16 -32 64 -128]
m     % Ismember. Implicit display
      % STACK: 1

```

# Answer
> 8 votes
# Octave, 28 bytes

```
@(n)any((-2).^(0:abs(n))==n)

```

This defines an anonymous function. The approach is similar to that in my MATL answer.

Try it online!

# Answer
> 8 votes
# Regex (ECMAScript / Java), ~~38~~ ~~37~~ ~~34~~ 33 bytes

```
\b(?=(^|x))((x*)\3\3(?=\3$))*x\1$

```

Try it online! \- ECMAScript
Try it online! \- Java

Takes its input in unary, as an optional `-` sign followed by a string of `x` characters, the count of which represents the absolute value of the number. (As such, it is not bijective unary, as zero can be represented in two ways. The regex works with both.)

Sets a flag for whether a negative sign is present. Operating on the absolute value, repeatedly divides by 4 (requiring that there is no remainder), and then asserts that the remaining number is 1 if there was no negative sign, or 2 if there was.

```
\b                    # Anchor on the border between {start or "-"} and "x"; in the
                      # domain of this problem, it is actually equivalent to
                      # (?<=^(?=x)|-|x$) - so it can anchor on the end instead of the
                      # beginning, but that would result in a non-match.
(?=(^|x))             # \1 = 1 if negative sign is present, 0 if not
(                     # loop the following:
    (x*)\3\3(?=\3$)   # assert tail is divisible by 4; tail = tail / 4
)*                    # iterate as many times as possible (minimum 0)
x                     # tail -= 1
\1                    # tail -= \1
$                     # assert tail==0

```

## Regex (ECMAScript), 36 bytes

```
^(-(x*)(?=\2$))?((x*)\4\4(?=\4$))*x$

```

Try it online!

This was the original version I posted; I'm keeping it here, as it's sufficiently different, yet close enough in length, to be interesting.

If it sees a negative sign, it strips it and divides the number by 2 (requiring that there is no remainder). It then asserts that the remaining number is a power of 4.

```
^
(
    -                 # eat a leading negative sign
    (x*)(?=\2$)       # assert tail is even; tail = tail / 2
)?                    # do the above optionally
# Assert that tail is a power of 4
(                     # loop the following:
    (x*)\4\4(?=\4$)   # assert tail is divisible by 4; tail = tail / 4
)*                    # iterate as many times as possible (minimum 0)
x$                    # assert tail == 1; if this fails to match, the regex engine will
                      # try backtracking the loops, but that cannot result in a match

```

# Regex (Perl / PCRE / Boost / Python / Ruby / .NET), 32 bytes

```
^(-)?((x*)\3\3(?=\3$))*x(?(1)x)$

```

Try it online! \- Perl
Try it online! \- PCRE2
Try it online! \- Boost
Try it online! \- Python
Try it online! \- Ruby
Try it online! \- .NET

Uses essentially the same algorithm as the 33 byte ECMAScript version, but in a more straightforward way, which never matches strings outside the problem's domain.

```
^
(-)?                  # \1 = negative sign if it is present; unset otherwise
(                     # loop the following:
    (x*)\3\3(?=\3$)   # assert tail is divisible by 4; tail = tail / 4
)*                    # iterate as many times as possible (minimum 0)
x                     # tail = tail - 1
(?(1)x)               # if \1 is set, then tail = tail - 1, else do nothing
$                     # assert tail == 0

```

---

# Regex (ECMAScript or better), 26 bytes

```
^((.*)\2\2(?=\2$))*(x|oo)$

```

Try it online! \- ECMAScript
Try it online! \- Perl
Try it online! \- Java
Try it online! \- Boost
Try it online! \- Python
Try it online! \- Ruby
Try it online! \- PCRE2
Try it online! \- .NET

Takes its input in bijective signed unary. A nonnegative number is a string of `x` characters, and a nonpositive number is a string of `o` characters. The the length of the string is the absolute value of the number.

```
^                     # tail = N = input number
(                     # Loop the following:
    (.*)\2\2(?=\2$)   # Assert tail is divisible by 4; tail = tail / 4;
                      # use "." so that either "x" or "o" can be matched, as
                      # long as all characters are identical.
)*                    # Iterate as many times as possible (minimum 0).
(x|oo)$               # Assert tail == 1 or tail == -2

```

# Answer
> 7 votes
**HP 28s 36 bytes**

```
WHILE DUP ABS 1 > REPEAT 2 NEG / END 1 ==

```

# Answer
> 6 votes
## JavaScript (ES6), 21 bytes

A recursive function that returns `0` or `true`.

```
f=n=>n==1||n&&f(n/-2)

```

### How it works

This doesn't include any explicit test -- like `n` being odd or `abs(n)` being less than one -- to stop the recursion early when the input is *not* an exact power of -2.

We exit only when `n` is exactly equal to either `1` or `0`.

This does work however because any IEEE-754 float will eventually be rounded to `0` when divided by 2 (or -2) enough times, because of arithmetic underflow.

### Test cases

```
f=n=>n==1||n&&f(n/-2)

console.log(f(-2));
console.log(f(-1));
console.log(f(0));
console.log(f(1));
console.log(f(2));
console.log(f(3));
console.log(f(4));
```

# Answer
> 6 votes
# PHP, 41 Bytes

```
for(;$argn%-2==0;)$argn/=-2;echo$argn==1;

```

# PHP, 52 Bytes

```
echo($l=log(abs($argn),2))==($i=$l^0)&&$argn>0^$i%2;

```

# PHP, 64 Bytes

Working with a Regex

```
echo preg_match("#^".($argn>0?1:"1+0")."(00)*$#",decbin($argn));

```

# Answer
> 6 votes
# C (gcc), 33 bytes

```
f(n){return n%2?n==1:n&&f(n/-2);}

```

Try it online!

# Answer
> 6 votes
# Python, 24 bytes

```
lambda n:n*n&n*n-1<n%3%2

```

Try it online!

The bit trick `k&k-1==0` checks whether `k` is a power of 2 (or `k==0`). Checking this for `k=n*n` as `n*n&n*n-1==0` tells us whether `abs(n)` is a power of 2.

To further see if `n` is a power of -2, we need only check that `n%3==1`. This works because mod 3, the value -2 is equal to 1, so its powers are 1. In contrast, their negations are 2 mod 3, and of course 0 gives 0 mod 3.

We combine the checks `n*n&n*n-1==0` and `n%3==1` into a single expression. The first can be written with `<1` for `==0`, since it's never negative. The `n%3==1` is equivalent to `n%3%2`, giving 0 or 1. So, we can combine them as `n*n&n*n-1<n%3%2`.

# Answer
> 6 votes
# 05AB1E, ~~5~~ 4 bytes

*Ties emanresu A's Vyxal answer for #1.*

```
2(вO

```

Try it online!

```
2(вO  # full program
   O  # push sum of...
  в   # list of base-10 values of base...
 (    # negative...
2     # literal....
  в   # digits of...
      # implicit input
      # implicit output

```

# Answer
> 5 votes
# Python 3, 34 bytes

```
lambda n:n==(-2)**~-n.bit_length()

```

# Answer
> 4 votes
# Java 7, 55 bytes

```
boolean c(int n){return n==0?0>1:n%-2==0?c(n/-2):n==1;}

```

**Explanation:**

```
boolean c(int n){  // Method with integer parameter and boolean return-type
  return n==0 ?    //  If n is zero:
    0>1//false     //   Return false
   : n%-2==0 ?     //  Else-if n mod -2 is zero:
    c(n/-2)        //   Recursive call for the input divided by -2
   :               //  Else:
    n==1;          //   Return if n is one
}                  // End of method

```

**Test code:**

Try it here.

```
class M{
  static boolean c(int n){return n==0?0>1:n%-2==0?c(n/-2):n==1;}

  public static void main(String[] a){
    for(int i = -2; i <= 4; i++){
      System.out.println(i + ": " + c(i));
    }
  }
}

```

**Output:**

```
-2: true
-1: false
0: false
1: true
2: false
3: false
4: true

```

# Answer
> 4 votes
# Perl 6, 21 bytes

```
{$_==(-2)**(.lsb//0)}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  $_                  # is the input
  ==                  # equal to
  (-2)**( .lsb // 0 ) # -2 to the power of the least significant bit of the input
}

```

Note that `0.lsb` returns `Nil` which produces a warning when used as a number, so the defined or operator `//` is used.
(Think of `//` as `||` with a different slant)

A method call with no invocant where a term is expected is implicitly called on `$_`. (`.lsb`)

Also works with`.msb`.

# Answer
> 4 votes
# Haskell, 24 23 bytes

```
f 0=0
f 1=1
f n=f(-n/2)

```

Defines a function `f` which returns `1` for powers of -2 and `0` otherwise.

A golfed version of my first submission to the other challenge.

# Answer
> 4 votes
# R, 22 bytes

Takes input from stdin, returns `TRUE` or `FALSE` accordingly.

```
scan()%in%(-2)^(0:1e4)

```

I'm not 100% sure that this is a valid answer, as it only works for integers up to R's size limit, and if the integers were unbounded it wouldn't work. However, the rules state:

> The usual integer overflow rules apply: your solution must be able to work for arbitrarily large integers in a hypothetical (or perhaps real) version of your language in which all integers are unbounded by default, but if your program fails in practice due to the implementation not supporting integers that large, that doesn't invalidate the solution.

In a hypothetical version of R which *does* allow unbounded integers, then we could use the following code, for the same byte count:

```
scan()%in%(-2)^(0:Inf)

```

Of course, in real R, the above code just gives `Error in 0:Inf : result would be too long a vector`.

# Answer
> 4 votes
# Julia 0.5, 20 bytes

```
!n=n∈(-2).^(0:n^2)

```

Try it online!

# Answer
> 4 votes
# Pyth, 7 bytes

```
!tsjQ_2

```

Test suite

Explanation:

```
     _2   # -2
   jQ     # Cast input to that base
          # Iff input is a power of -2, then jQ_2 returns something of the form [1]+[0]*n
          # where n is the power of -2
          # This is also the only situation in which the sum of that is 1
!ts       # so we check for that: is the (s)um equal to 1 (or, equivalently, "!(sum - 1)" )

```

# Answer
> 4 votes
# Risky, 14 bytes

```
__-+_-2{[?+_0:__0+_0+__?+_0

```

Try it online!

**Explanation:**

* `__-+_-`: `-2`, written as `-1 + -1` with padding
* `2`: Power
* `{[?+_0`: `log_2(abs(input))`, with `+_0` as padding
* `:`: Equals
* `__0+_0+__?+_0`: Input (`?`), with padding

So basically, `-2 ** log_2(abs(input)) == input`

# Answer
> 4 votes
# x86-32 machine code, ~~20 18~~ 16 bytes

-2 bytes thanks to @xiver77 -2 bytes by removing an unnecessary jump

(This submission was originally 19 bytes, but I adjusted it to 20 since I forgot to add `ret`).

```
00000000: f8a9 ffff 7f00 7507 c1f8 1730 e0d1 f8c3  ......u....0....

```

Try it online!

Expects a single precision float in `eax`. Output is in the carry flag.

It takes advantage of some fundamental properties of floats, for some power of -2 `n`:

* `abs(n)` is a power of 2, therefore `n`'s mantissa must be 0.
* `n` is positive for odd numbered exponents, and negative for even exponents. In other words, `sign ^ exponent[0] = 1` where `exponent[0]` is the least significant bit of the exponent.

NASM source:

```
[BITS 32]

isnegpow2:
    ; Clear carry
    clc
    ; Check if mantissa is non-zero
    test eax, 0x7fffff
    ; If it is, then abs(eax) is not a
    ; power of 2, so eax cannot be a power
    ; of -2
    jnz .end

    ; Shift away the mantissa
    sar eax, 23
    ; Now ah contains the sign,
    ; and al contains the exponent.
    ; For powers of -2, sign ^ exponent[0] = 1
    xor al, ah
    ; Check lsb by shifting it to the carry flag
    ; If it's 1, then eax is a power of -2, so the
    ; carry will be set
    sar eax, 1
.end:
    ret

```

# Answer
> 3 votes
# Javascript(ES7), 45 bytes

```
x=>-1**Math.log2(Math.abs(x))*Math.abs(x)==x

```

# Answer
> 3 votes
# Prolog (SWI), 44 bytes

```
p(X):-X=1;X\=0,X mod 2=:=0,Z is X/(-2),p(Z).

```

Online interpreter

# Answer
> 3 votes
# bc 88 bytes

```
bc -l <<< "n=$1;q=l(sqrt(n*n));p=4*a(1);((n<1)*c(q/l(2)*p/2)+(n>1)*(s(q/l(4)*p)))^2==0"

```

I have this in a file `neg2.sh` and it prints `1` for powers of `-2` and `0` otherwise

I know it's really long, but it was fun

### Test

```
$ for i in {-129..257}; do echo -n "$i: "; ./neg2.sh $i; done | grep ': 1'
-128: 1
-32: 1
-8: 1
-2: 1
1: 1
4: 1
16: 1
64: 1
256: 1

```

### Explanation

The main body has two halves, both are trying to equal zero for powers of `-2`.

```
q=l(sqrt(n*n))               % ln of the absolute value of the input
p=4*a(1)                     % pi: arctan(1) == pi/4
q/l(2) -> l(sqrt(n*n))/l(2)  % change of base formula -- this gives
                             % the power to which 2 is raised to equal
                             % sqrt(n*n). It will be an integer for
                             % numbers of interest
n<1                          % 1 if true, 0 if false. for negative
                             % numbers check for powers of 2
n>1                          % for positive numbers, check for powers
                             % of 4
c(q/l(2)*p/2)                % cos(n*pi/2) == 0 for integer n (2^n)
s(q/l(4)*p)                  % sin(n*pi) == 0 for integer n (4^n)
(....)^2==0                  % square the result because numbers are
                             % not exactly zero and compare to 0

```

# Answer
> 3 votes
# Casio BASIC, 76 bytes

Note that 76 bytes is what it says on my calculator.

```
?→X
0→O
While Abs(X)≥1
X÷-2→X
If X=1
Then 1→O
IfEnd
WhileEnd
O

```

This is my first venture into Casio BASIC... I never realised I could write such decent programs on a calculator :D

# Answer
> 3 votes
# APL (Dyalog Extended), 10 bytes

-3 thanks to @rak1507

```
⊢∊¯2*⍳∘|

```

Try it online!

# Answer
> 3 votes
# K (ngn/k), 14 bytes

```
{|/x=*\1,x#-2}

```

Try it online!

* `*\1,x#-2` return list of -2 raised from 0 to `x`, i.e. (`1 -2 4 -8`)
* `|/x=` are any items in that list equal to `x`?

# Answer
> 3 votes
# Vyxal `r`, 6 bytes

```
ȧʀudec

```

Try it Online!

Very rude, I know, but it gets the job done.

## Explained

```
ȧʀudec
ȧʀ     # range(0, abs(input) + 1)
  ud   # -2 (-1 * 2). 2N would have worked just the same, but that wouldn't be as funny now would it.
    e  # -2 ** the range (vectorises)
     c # is input in ^

```

# Answer
> 3 votes
# Brachylog, 10 bytes

```
1|¬0&~×₂ṅ↰

```

Try it online!

### Explanation

A recursive solution:

```
1|          Either the input is 1 (base case), or...
  ¬0        The input is not 0
    &       and
     ~×₂    some integer times 2 equals the input
        ṅ   Negate that integer
         ↰  and call the predicate recursively

```

# Answer
> 3 votes
# Brachylog, 7 bytes

```
ḃb-₂ᵐ×?

```

Try it online! Or, verify all inputs from -8 to +16.

### Explanation

```
ḃ        Convert to binary, ignoring the sign (so -2 and 2 both become [1,0])
 b       Behead: remove the first element
  -₂ᵐ    Subtract 2 from each element
     ×   Product of that list
      ?  Assert that the result equals the original input number

```

Some examples to show how this works:

```
         -8          1    2      0    6
ḃ        [1,0,0,0]   [1]  [1,0]  [0]  [1,1,0]
 b       [0,0,0]     []   [0]    []   [1,0]
  -₂ᵐ    [-2,-2,-2]  []   [-2]   []   [-1,-2]
     ×   -8          1    -2     1    2

```
* If the number is \\$(-2)^n\\$ for some integer \\$n\\$, `ḃb` produces a list of \\$n\\$ zeros; subtracting 2 from each turns it into a list of \\$n\\$ copies of \\$-2\\$, and taking the product gives us \\$(-2)^n\\$ again.
* If the number is \\$-(-2)^n\\$, we get \\$(-2)^n\\$ instead, which doesn't match the input.
* For any other number, `ḃb` gives a list containing some amount of \\$-2\\$ mixed with \\$-1\\$. The product of this list is \\$\pm2^m\\$ for some \\$m\\$; but since our input is not of the form \\$\pm2^m\\$, it doesn't match.

# Answer
> 3 votes
# TI-Basic, 14 bytes

```
max(Ans=(-2)^randIntNoRep(0,abs(Ans

```

Takes input in `Ans`. `randIntNoRep(0,` can be replaced with `cumSum(1 or rand(` for greater compatibility and +4 bytes. `-` represents the negative sign.

Faster but larger answer that works for larger numbers:

### ~~20~~ 19 bytes

```
Ans=(-2)^int(log(abs(Ans)+not(Ans),2

```

# Answer
> 2 votes
# Retina, 27 bytes

```
+`(1+)\1
$1_
^(1|-1_)(__)*$

```

Try it online!

Takes input in unary, which is fairly standard for Retina. The first two lines do partial unary to binary conversion based on the first two lines of code from the Tutorial entry (any extraneous `1`s will cause the match to fail anyway), while the last line checks for a power of four or a negative odd power of two.

```
+`(1+)\1\1\1
$1_
^(-1)?1_*$

```

Try it online!

This time I do partial unary to base four conversion. Powers of four end up as `^1_*$` while negative odd powers of two end up as `^-11_*$`.

```
+`\b(1111)*$
$#1$*
^(-1)?1$

```

Try it online!

This time I just keep dividing by four as much as I can and check for `1` or `-11` at the end.

```
+`\b(1+)\1\1\1$
$1
^(-1)?1$

```

Try it online!

Another way of dividing by four. And still annoyingly 27 bytes...

# Answer
> 2 votes
# Fourier, 53 bytes

```
I~X1~N~G0(0-2*G~GX*X~PG*G>P{1}{0~O~N}G{X}{1~O0~N}N)Oo

```

I'll work on golfing this later, but the outline of this is:

```
X = User input
G = N = 1
Loop until N = 0
    G = -2 * G
    P = X*X
    If G*G > P then
        N = O = 0
    End if
    If G = X then
        O = 1
        N = 0
    End if
End loop
Print O

```

Where the output is `0` for *falsey* and `1` for *truthy*.

Try it online!

# Answer
> 2 votes
# Javascript ES6, ~~51~~ 50 chars

Not very short, but I hope interesting :)

```
x=>eval(`for(w=q=1;w<=(x<0?-x:x);w*=2,q*=-2)q==x`)

```

Test:

```
f=x=>eval(`for(w=q=1;w<=(x<0?-x:x);w*=2,q*=-2)q==x`)
for(x=-2049; x<2049; ++x) if(f(x)) console.log(x)
```

# Answer
> 2 votes
## Alice, 12 bytes, non-competing

```
/o|\ntzR2
@i

```

Try it online!

### Explanation

Alice has a fairly weird built-in, which was added because I needed something that goes well thematically with the string operation "discard everything up to this substring". That operation is "drop small factors" and what it does for positive **x** and **y** is that it divides **x** by all of its prime factors less than or equal to **y**. But if **y** is negative, then Alice tries negative prime factors greater than or equal to **y** instead, which means that every time a prime factor is removed, the sign of **x** changes. So if we use **-2** as the second argument, we'll end up with **1** if and only if the input is a power of **-2** (if the input is not a power of two, other factors will remain in the end, and if it has the wrong sign, we'll end up with **-1** instead of **1**).

The rest of the program is just a bit of weird control flow.

```
/   Reflect southeast. Switch to Ordinal.
i   Read all input as a string.
    Reflect off boundary, move northeast.
|   Reflect northwest.
    Reflect off boundary, move southwest.
i   Read all input as a string, but there's no input left, so this pushes "".
    Reflect off boundary, move northwest.
/   Reflect west. Switch to Cardinal.
    Wrap around to the end of line 1.
2R  Push -2. (Really: push 2, negate.)
z   Drop small factors. When trying to find a second integer argument,
    this discards the empty string and then implicitly converts the input
    string to an integer. Turns only valid inputs to 1.
tn  Decrement, logical NOT. Effectively an "equals 1?" check.
\   Reflect southwest. Switch to Ordinal.
    Reflect off boundary, move northwest.
o   Implicitly convert result to a string and print it.
    Reflect off boundary, move southwest.
@   Terminate the program.

```

# Answer
> 2 votes
# Clojure, 57 bytes

```
(defn i[n](if(= n 1)true(if(=(int n)0)false(i(/ n -2)))))

```

Try it online!

Full function, with annotations:

```
;; Define function `is-pow?` with 1 argument, `n`
(defn is-pow? [n]
  ;; If n = 1, that means it's a power of -2,
  ;; so we return true
  (if (= n 1) true
    ;; When we recursively call the function,
    ;; -1 > n > 1. `int` rounds up when the number
    ;; is negative (`(int -1/2)` = 0), and rounds down
    ;; when the number is positive. It also catches
    ;; the edgecase of 0.
    (if (= (int n) 0) false
      ;; If n made it to here, n < -1 or n > 1 - we have
      ;; to call the function recursively.
      (is-pow? (/ n -2)))))

```

# Answer
> 2 votes
# Common Lisp, 51 bytes

```
(defun f(n)(or(= 1 n)(and(< 1(abs n))(f(/ n -2)))))

```

Recursive version. Try it online.

# Answer
> 2 votes
# Excel, 28 bytes

```
=(-2)^INT(LOG(ABS(B2),2))=B2

```

Or using approach from @Martin Ender's Mathematica approach:

**29 bytes**

```
=ISEVEN(LOG(MAX(B1,-2*B1),2))

```

# Answer
> 2 votes
# Perl 5 `-p`, 32 bytes

```
$.*=-2while(abs)>abs$.;$_=$.==$_

```

Try it online!

# Answer
> 2 votes
# Rust, 41 bytes

```
|x|(|mut e|{while e*e<x*x{e*=-2}e==x})(1)

```

Try it online!

# Answer
> 2 votes
# Python 3.8 (pre-release), 39 bytes

```
lambda n:len(x:=bin(n))&1==x.count('1')

```

Try it online!

# Answer
> 2 votes
# PowerShell, 102 bytes

```
$a=$n-replace'-';$p=[convert]::ToString($a,2).length-1;if([math]::pow(-2,$p)-eq$n){return !0}return !1

```

Try it online!

Ungolfed:

```
-2..4 | %{                                  # for loop from -2 to 4
    $n=$_                                   # setting n to current number in loop
    $a = $n-replace'-'                      # getting absolute value of num
    $p=[convert]::ToString($a,2).length-1   # converting to binary and counting 0s (2^p)

    if([math]::pow(-2,$p) -eq $n){          # seeing if -2^p is equal to the original num
        return !0                           # returns not 0 or True
    }

    return !1                               # returns not 1 or False
}

```

# Answer
> 1 votes
## Python 2.7, 40 bytes

```
a=input()
while a%-2==0:a/=-2
print a==1

```

Credits to Mr. Xcoder for the original code of length 43 bytes. Had to post as a separate answer since I don't have enough reputation to comment.

# Answer
> 1 votes
# Cjam, 12 bytes

```
li_z2mLi-2#=

```

Explanation comes later.

# Answer
> 1 votes
# Scheme, 60 bytes

```
(define(f n)(cond((= 1 n)#t)((<(abs n)1)#f)(#t(f(/ n -2)))))

```

Recursive solution.

# Answer
> 1 votes
**Axiom, 50 bytes**

```
g(n:INT):INT==(n=0 or n=1=>n;n rem 2=0=>g(n/-2);0)

```

It would return 0 if n is not power of (-2), else return 1; exercises

```
(70) -> n:=-10000;repeat(if g(n)=1 then output n; n>10000=>break;n:=n+1)
   - 8192
   - 2048
   - 512
   - 128
   - 32
   - 8
   - 2
   1
   4
   16
   64
   256
   1024
   4096

```

# Answer
> 1 votes
# Jelly, 6 bytes

```
AḶ-2*i

```

Try it online!

Explanation:

```
        Argument: -8
A       Get the absolute value of n             8
 Ḷ      Create a range from 0 to that number-1  0, 1, 2, 3, 4, 5, 6, 7
  -2*   converts that range into the list       -2^0, -2^1, ..., -2^7
     i  Returns >0 if n is in this range, 0 otherwise.

```

Dennis pointed out a flaw in my approach, which I fixed by taking the absolute value of the input for the range generation.

# Answer
> 1 votes
# C#, ~~104~~ 107 bytes

+3 bytes, for using system, and finding another method to count bits

```
using System;b=>Enumerable.Range(0,1+(int)Math.Log(int.MaxValue,2)).Select(x=>Math.Pow(-2,x)).Any(x=>b==x);

```

It uses Linq to calculate all of -2-s integer powers, and then to test if the input is one them. It would be a bit shorter, if it didn't have to work in a theoretical version, where int can be of any size. Ungolfed:

```
bool IsPowerOfMinus2(int number)
{
    return Enumerable.Range(0, 2 + (int)Math.Log(int.MaxValue, 2))
        // We generate an IEnumerable, with values from 0 to the length of
        // maximum number in binary. We need to add one, because we need to
        // know, how many integers to
        .Select(x => Math.Pow(-2, x))
        //Replace every number with -2 raised to the number
        .Any(x => number == x);
        //Determine, if the input is one of them
}

```

# Answer
> 1 votes
# Pxem, 53 bytes (filename).

Been a while since my last post of Pxem.

Backslash followed by three digits of octet: a character whose codepoint is so:

```
._.c\001.y\001.r.-\002.!XX.a.c\003.x.c\004.%.w.d.a\004.$.c\003.a\001.z.d.aY.o

```

Try it online! Through this problem I noticed a bug in my interpreter. Maybe I need to redesign the interpreter; shortening the code makes maintainance difficult.

## Usage

* As a string of decimal integer from stdin for input.
* Outputs a letter Y for truthy; nothing for falsey.

```
XX.z
# push an integer of input
.a._XX.z
# NOTE Pxem does not have negative constants
# So negative inputs must be changed to positive
# and then get multiplied by two
.a.c\001.y\001.r.-\002.!XX.aXX.z
# Pxem does not have log() nor something similar
# Just keep dividing by four
# And exit if it seemed not to be 4^n
.a.c\003.xXX.z
  .a.c\004.%.w.d.aXX.z
  .a\004.$XX.z
.a.c\003.aXX.z
# final check for <4
.a\001.z.d.aY.o

```

# Answer
> 1 votes
# x86\_(32/64) machine code, 23 bytes

```
\x0f\xbc\xc1\xf3\x0f\xb8\xc9\xa8\x01\x74\x06\x01\xc8\x3c\x20\xf5\xc3\x83\xf9\x01\x74\xf9\xc3

```

Try it online!

This is a kind of problem for which the CPU usually has a built-in instruction to solve it easily but most high level languages don't support it straightforwardly.

Two x86 instructions does the main job.

* `bsf` \- count trailing zeros (bit-scan forward)
* `popcnt` \- count bits set

The `bsf` type of instruction is very common on many architectures with varying names. `popcnt` is a less popular one, but ARM and RISC-V also supports it as an extension.

### algorithm

When you look at the binary representation of an integer power of -2, you can see a pattern.

```
16 -> 10000
4 -> 100
1 -> 1
-2 -> ..110
-8 -> ..11000
-32 -> ..1100000

```

When the trailing-zero count is even, there is one bit set. When the trailing-zero count is odd, the sum of this and the set-bit count equals the word size.

### assembly

```
; out: carry flag, in: eax = 1, ecx = arg
entry:
    bsf eax, ecx
    ; if ecx == 0 then eax == 1
    ; relies on an undocumented behaviour (for Intel)
    popcnt ecx, ecx
    test al, 1
    jz even
    add eax, ecx
    cmp al, 32
flip:
    cmc
    ret
even:
    cmp ecx, 1
    je flip
    ret

```

# Answer
> 1 votes
# , ~~21~~ 17 bytes

```
+/@(=_2:^i.@>:@|)

```

Try it online!

# Answer
> 1 votes
# Vyxal, 4 bytes

```
2Nτ∑

```

Try it Online!

Port of Makonede's 05AB1E answer, outputting 1 for truthy and anything else for falsy.

```
   ∑ # Is exactly one of
  τ  # Digits in base...
2N   # -2
     # Truthy?

```

# Answer
> 1 votes
# Pyt, 9 bytes

```
ĐÅř⁻2~⇹^∈

```

Try it online!

```
Đ            implicit input; Đuplicate
 Å           Åbsolute value
  ř          řangify [1,2,...,n]
   ⁻         decrement
    2~       push 2; negate
      ⇹^     swap top two items; element-wise exponentiation
        ∈    is the input in the resultant list?; implicit print

```

# Answer
> 1 votes
# Thunno, \\$ 10 \log\_{256}(96) \approx \\$ 8.23 bytes

```
DZAR2n@sAq

```

Attempt This Online!

Port of Emigna's 05AB1E answer.

#### Explanation

```
DZAR2n@sAq  # Implicit input
DZA         # Duplicate and push abs(input)
   R        # Push range(0, abs(input))
    2n@     # Push 2 ** each of the above
       sAq  # Is the input in this list?
            # Implicit output

```

# Answer
> 1 votes
# Go, 55 bytes

```
func f(n int)bool{for;n%2==0&&n!=0;n/=-2{}
return n==1}

```

Attempt This Online!

Repeatedly divides the input until it's not even or zero. Then it returns whether it's equal to 1 (if it's a 1, then it's a power of -2).

# Answer
> 1 votes
# Thunno 2, 7 bytes

```
AĖuḌ@$Ƈ

```

Attempt This Online!

#### Explanation

```
AĖuḌ@$Ƈ  # Implicit input       ->  -8
A        # Absolute value       ->  8
 Ė       # Push [0..n]          ->  [0,1,2,3,4,5,6,7,8]
  uḌ     # Push -2              ->  [0,1,2,3,4,5,6,7,8]  2
    @    # Exponentiate         ->  [1,-2,4,-8,16,-32,64,-128,256]
     $Ƈ  # Contains the input?  ->  1
         # Implicit output

```

# Answer
> 0 votes
# Japt `-!`, ~~7~~ 6 bytes

```
ì´J Åx

```

Try it

---
Tags: code-golf, decision-problem, integer
---


# Question
Title: The Luhn algorithm for verifying credit card numbers, etc
### Challenge

Write the shortest program or function to calculate the Luhn Algorithm for verifying (credit card) numbers.

### Luhn algorithm explained

From RosettaCode, this algorithm for the purposes of this challenge is specified as such, with the example input of `49927398716`:

```
Reverse the digits, make an array:
    6, 1, 7, 8, 9, 3, 7, 2, 9, 9, 4
Double the numbers in odd indexes:
    6, 2, 7, 16, 9, 6, 7, 4, 9, 18, 4
Sum the digits in each number:
    6, 2, 7, 7, 9, 6, 7, 4, 9, 9, 4
Sum all of the numbers:
    6 + 2 + 7 + 7 + 9 + 6 + 7 + 4 + 9 + 9 + 4 = 70
If the sum modulo 10 is 0, then the number is valid:
    70 % 10 = 0 => valid

```

### IO Rules

**Input**: A string or number (your choice), in your language's input/output format of choice

**Output**: A truthy or falsy value, respectively, indicating whether or not the input is valid according to the test above.

### Notes / Tips

* Try not to accidentally post your own credit card or account numbers, if you use them to test :)
* If the input is invalid and impossible to process **with the specified algorithm** (i.e, too short to work with), you can do whatever you want, including blow up my computer.
* **However**, the previous bullet does not mean that your language can do whatever it wants with Numbers that are too large for it to handle. If your language isn't capable of handling a test case, then consider taking a string as input.

### Examples

The following examples were validated with this Python script; if you think one is wrong or have a question, just ping @cat.

```
49927398716      True
49927398717      False
1234567812345670 True
1234567812345678 False
79927398710      False
79927398711      False
79927398712      False
79927398713      True
79927398714      False
79927398715      False
79927398716      False
79927398717      False
79927398718      False
79927398719      False
374652346956782346957823694857692364857368475368 True
374652346956782346957823694857692364857387456834 False
8 False **
0 True  **

```

\** according to the Python implementation, but you may do anything because these are too short to be eligible by a strict adherence to the specification.

---

If any of the above invalidates existing answers (though I believe that should not be possible), then those answers are stil valid. However, **new** answers, in order to be valid, should follow the specification above.

### Leaderboard

```
var QUESTION_ID=22,OVERRIDE_USER=73772;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}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="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <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><div id="language-list"> <h2>Winners 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><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>
```

# Answer
## Golfscript - 24 chars

```
-1%{2+0!:0)*109%+}*10%8=

```

Explanation:

1. `-1%` reverses the string
2. `{` begins a block (which we use as a loop). Each character in the strings is pushed as it's ascii value.
    1. `2+` adds 2. (the ascii value of a digit is 48+n, so we have 50+n now and the last digit is n)
    2. `0!:0` inverts the value of 0 and stores it (everything is a variable), so we have 1 on the first iteration, 0 on the second, etc.
    3. `)*` adds one to this value and multiplies it, so we multiply by 2, then 1, then 2, etc.
    4. `109%` is remainder modulo 109. This affects only values 5-9 which have been doubled and reduces them to the correct value.
    5. `+` adds this value to the running sum
3. `}*` ends the block and does a 'fold' operation. First, the first character is pushed (since we have reversed, this is the check digit). Then, alternate pushing and executing the block. Thus, we are using the first character's ascii value as the starting value for the running sum.
4. `10%` takes the remainder modulo 10.
5. `8=` will return 1 if the value is 8. We use this because we did not normalize the first pushed character (the check digit).

One might think that we could use `8-` instead of `2+` to save a character by changing `109%` to `89%`, except then we would need to add a space so the `-` is subtraction (instead of `-0`).
> 24 votes

# Answer
## GolfScript, 44 chars

```
-1%{16%}%2/1,\+{(\.{0=2*.9>9*-+}{;}if+}*10%!

```

---

**Selected commentary**

Interestingly, the first two items below demonstrate three completely different uses of the `%` operator: array selection, map, and mod. Most GolfScript operators are "context-sensitive", giving them hugely divergent behaviours depending on what types the arguments are.

1. `-1%` reverses the string. This is important as the digit pairs are counted from the right.
2. `{16%}%` converts all the ASCII digits into numbers, by modding them with 16.
3. `2/` splits the array into groups of 2.
4. `1,` is a cheap way to do `[0]`.
5. `\+` effectively prepends the 0 to the digits array. It does this by swapping then concatenating.

The 0 is prepended in preparation for the fold that comes in next. Rather than taking an explicit initial value, GolfScript's fold uses the first item in the array as the initial value.

Now, let's look at the actual fold function. This function takes two arguments: the folded value, and the current item on the array (which in this case will be an array of 2 or (uncommonly) 1, because of the `2/` earlier). Let's assume the arguments are `1 [2 3]`.

1. `(\.` splits out the leftmost array element, moves the remaining array to the front, then copies it. Stack now looks like: `1 2 [3] [3]`.
2. The `if` checks if the array is empty (which is the case for the last group when dealing with an odd-sized account number). If so, then no special processing happens (just pop off the empty array).
3. For an even group:
    1. `0=` grabs the first (only, in this case) element of the array. `1 2 3`
    2. `2*` doubles the number. `1 2 6`
    3. `.9>9*-` subtracts 9 from the number if it's greater than 9. Implemented as: copy the number, compare with 9, multiply the result (which is either 0 or 1) with 9, then subtract. `1 2 6`
    4. `+` finally adds that to the first number. `1 8`
4. `+` (after the `if`) adds the result of the `if` to the original value, resulting in the new folded value.

After the folding completes, we simply mod with 10 (`10%`), and negate the result (`!`), so that we return 1 iff the sum is a multiple of 10.
> 11 votes

# Answer
## Python, 73 69 characters

```
def P(x):D=map(int,x);return sum(D+[d-d/5*9for d in D[-2::-2]])%10==0

```
> 11 votes

# Answer
# Python 3, 77 bytes

```
c=lambda a:sum(sum(divmod(int(a[-e-1])<<e%2,10))for e in range(len(a)))%10==0

```
> 10 votes

# Answer
**C# 119 characters:**

```
bool l(string n){return(String.Join("",n.Reverse().Select((x,i)=>(x-48)*(i%2<1?1:2)+"").ToArray()).Sum(x=>x-48))%10<1;}

```

Not *too* bad for a code golf n00b in a statically typed language, I hope.

This can be reduced to **100**:

```
bool l(string n){return String.Join("",n.Reverse().Select((x,i)=>(x-48)*(i%2+1))).Sum(x=>x+2)%10<1;}

```
> 10 votes

# Answer
# PHP, 108 bytes

```
<?function v($s,$t=0){for($i=strlen($s);$i>=0;$i--,$c=$s[$i])$t+=$c+$i%2*(($c>4)*-4+$c%5);return!($t % 10);}

```
> 8 votes

# Answer
## Golfscript - 34 chars

```
{15&}%.-2%\);-2%{.+(9%)}%+{+}*10%!

```

Example number from wikipedia page 4992739871

```
{15&}%  does a bitwise and of each ascii digit with 00001111
        now I have a list of digits
        [4 9 9 2 7 3 9 8 7 1 6]
.       makes a copy of the list, now I have two identical lists
        [4 9 9 2 7 3 9 8 7 1 6] [4 9 9 2 7 3 9 8 7 1 6]
-2%     like [::-2] in python takes every second element in reverse
        [4 9 9 2 7 3 9 8 7 1 6] [6 7 9 7 9 4]
\       swap the two lists around
        [6 7 9 7 9 4] [4 9 9 2 7 3 9 8 7 1 6]
);      drop the last digit off the list
        [6 7 9 7 9 4] [4 9 9 2 7 3 9 8 7 1]
-2%     same as before
        [6 7 9 7 9 4] [1 8 3 2 9]
{       for each item in the list ...
.+      ... double it ...
(       ... subtract 1 ...
9%      ... mod 9 ...
)}%     ... add 1 ...
        [6 7 9 7 9 4] [2 7 6 4 9]
+       join the two lists
        [6 7 9 7 9 4 2 7 6 4 9]
{+}*    add the elements up
        70
10%     mod 10
        0
!       invert the result
        1

```
> 8 votes

# Answer
# Haskell, 96 bytes

There must be a better/shorter way, but here's my **Haskell** solution in **96 characters**:

```
l=(==0).(`mod`10).sum.zipWith($)(cycle[id,\x->x`mod`5*2+x`div`5]).reverse.map((+(-48)).fromEnum)

```

Sadly the `digitToInt` function can only be used if you `import Data.Char` first. Otherwise I could get down to 88 characters by replacing `((+(-48)).fromEnum)` with  `digitToInt`.
> 7 votes

# Answer
## Ruby - 85 characters

```
def f s
l=s.size
s.chars.map{|k|(i=k.to_i*((l-=1)%2+1))%10+i/10}.inject(:+)%10==0
end

```
> 7 votes

# Answer
# D, 144 bytes

```
bool f(S)(S s){int t(C)(C c){return to!int(c)-'0';}int n,v;foreach(i,c;array(retro(s))){v=i&1?t(c)*2:t(c);n+=v>=10?v%10+v/10:v;}return n%10==0;}

```

More legibly:

```
bool f(S)(S s)
{
    int t(C)(C c)
    {
        return to!int(c) - '0';
    }

    int n, v;

    foreach(i, c; array(retro(s)))
    {
        v = i & 1 ? t(c) * 2 : t(c);

        n += v >= 10 ? v % 10 + v / 10 : v;
    }

    return n % 10 == 0;
}

```
> 6 votes

# Answer
## Windows PowerShell, 82

```
filter f{!((''+($_[($_.length)..0]|%{+"$_"*($i++%2+1)})-replace'.','+$&'|iex)%10)}

```

History:

* 2011-02-13 03:08 (84) First attempt.
* 2011-02-13 12:13 (82) I don't need to join, as spaces do not hurt. `+1 + +3` can still be evaluated.
> 6 votes

# Answer
# Jelly, ~~12~~ ~~11~~ 9 bytes

```
ṚḤÐeDFS⁵ḍ

```

Try it online!

## How it works

```
ṚḤÐeDFS⁵ḍ - Main link. Takes an integer n on the left
Ṛ         - Cast n to digits and reverse
  Ðe      - To values at even indices:
 Ḥ        -   Unhalve; Double
    D     - Cast to digits
     F    - Flatten
      S   - Sum
        ḍ - Divisible by:
       ⁵  - 10?

```
> 6 votes

# Answer
## PowerShell 123

```
filter L($x){$l=$x.Length-1;$l..0|%{$d=$x[$_]-48;if($_%2-eq$l%2){$s+=$d}elseif($d-le4){$s+=$d*2}else{$s+=$d*2-9}};!($s%10)}

```
> 5 votes

# Answer
# Q, 63

```
{0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]}

```

usage

```
q){0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]}"79927398711"
0b
q){0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]}"79927398712"
0b
q){0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]}"79927398713"
1b

```
> 5 votes

# Answer
# APL, 28 bytes

```
{0=10|+/⍎¨∊⍕¨v×⌽2-2|⍳⍴v←⍎¨⍵}

```

**Exploded view**

```
{                     v←⍎¨⍵}  ⍝ turn the string into a numeric vector of its digits, v
                2-2|⍳⍴v       ⍝ make a vector of the same length, with 2 in every 2nd place
             v×⌽              ⍝ multiply it with v, starting from the right
          ∊⍕¨                 ⍝ turn each component into a string and collect all the digits
      +/⍎¨                    ⍝ turn each digit again into a number and sum them
 0=10|                        ⍝ check whether the sum is a multiple of 10

```

**Examples**

```
      {0=10|+/⍎¨∊⍕¨v×⌽2-2|⍳⍴v←⍎¨⍵} '79927398713'
1
      {0=10|+/⍎¨∊⍕¨v×⌽2-2|⍳⍴v←⍎¨⍵} '123456789'
0

```
> 5 votes

# Answer
# x86-16 machine code, 27 bytes

Binary:

```
00000000: bb00 0103 f1fd ac2c 30f6 df78 06d0 e0d4  .......,0..x....
00000010: 0a02 dc02 d8e2 ef93 d40a c3              ...........

```

Listing:

```
BB 0100         MOV  BX, 100H           ; running sum (BL) to 0, BH to a positive value
03 F1           ADD  SI, CX             ; start at end of input string
FD              STD                     ; set LODSB direction to decrement
            DIGIT_LOOP:
AC              LODSB                   ; load next digit into AL, decrement SI
2C 30           SUB  AL, '0'            ; convert ASCII char to binary value
F6 DF           NEG  BH                 ; flip sign of BH to alternate odd/even index
78 06           JS   IS_EVEN            ; if not odd index, do not double
D0 E0           SHL  AL, 1              ; double the value
D4 0A           AAM                     ; split digits (ex: 18 --> AH = 1, AL = 8)
02 DC           ADD  BL, AH             ; add tens digit to running sum
            IS_EVEN:
02 D8           ADD  BL, AL             ; add ones digit to running sum
E2 EF           LOOP DIGIT_LOOP
93              XCHG AX, BX             ; sum is in BL, move to AL for mod 10 check
D4 0A           AAM                     ; ZF = ( AL % 10 == 0 )
C3              RET                     ; return to caller

```

Uses (abuses) x86's BCD-to-binary instruction `AAM` to handle the individual digit splitting and `modulo 10` check.

Callable function, input card num string pointer in `SI`, length in `CX`. Output: `ZF` if valid.

**Example test program output:**

## Alternate version, 29 bytes

```
33 DB           XOR  BX, BX             ; running sum (BL) to 0
03 F1           ADD  SI, CX             ; start at end of string
4E              DEC  SI                 ; align for WORD
FD              STD                     ; set LODSB direction to decrement
            DIGIT_LOOP:
AD              LODSW                   ; load next two digits into AH:AL, dec SI by 2
25 0F0F         AND  AX, 0F0FH          ; convert ASCII chars to binary value
02 DC           ADD  BL, AH             ; add ones digit of even index to sum
49              DEC  CX                 ; decrement counter for WORD
74 0A           JZ   DONE               ; if input is odd length, will be 0 at the end
D0 E0           SHL  AL, 1              ; double the value
D4 0A           AAM                     ; split digits (ex: 18 --> AH = 1, AL = 8)
02 DC           ADD  BL, AH             ; add tens digit to sum
02 D8           ADD  BL, AL             ; add ones digit to sum
E2 ED           LOOP DIGIT_LOOP
            DONE:
93              XCHG AX, BX             ; move sum to AL for mod 10 check
D4 0A           AAM                     ; ZF = ( AL % 10 == 0 )
C3              RET                     ; return to caller

```

This version loads two digits at the same time, eliminating the flip/flop branch. The issue here is having to check for an odd number of digits on the input and discard the value in memory right before the beginning of the string once it reaches the last word. Obviously not shorter, but perhaps someone clever can golf it more!
> 5 votes

# Answer
# Perl, ~~46~~ ~~42~~ 41 bytes

Includes +1 for `-p`

Give input on STDIN:

```
luhn.pl <<< 79927398713

```

`luhn.pl`:

```
#!/usr/bin/perl -p
s%.%$=-=-$&-$&*1.2*/\G(..)+$/%eg;$_=/0$/

```
> 4 votes

# Answer
# 05AB1E, ~~12~~ 10 bytes

```
RSāÈ>*SOTÖ

```

Try it online! or as a Test Suite

**Explanation**

```
R             # reverse input
 S            # split to list of digits
  ā           # push range[1 ... len(input)]
   È          # map isEven on each
    >         # increment
     *        # multiply doubling every other item
      SO      # sum digits
        TÖ    # mod 10 == 0

```
> 4 votes

# Answer
# C (clang), ~~264~~ ~~212~~ ~~196~~ ~~175~~ 172 bytes

```
l,x;main(i){char*s;gets(s);int n[i=l=strlen(s)];for(;i--;)n[i]=s[i]-48;for(;(i+=2)<l;n[i]>9?n[i]=n[i]/10+n[i]%10:0)n[i]*=2;for(;l--;)x+=n[l];printf(x%10<1?"True":"False");}

```

Try it online!

Simply the basic way of programming the algorithm, but all whitespace is removed. All I could say is that there are a bunch of for-loops in this one.

Thanks to ceilingcat for golfing 52 bytes, another 16 bytes, and another 21 bytes, and another 3 bytes.
> 4 votes

# Answer
## JavaScript 1.8: 106 characters

This is an original solution I came up with before I found this post:

```
function(n){return!(n.split('').reverse().reduce(function(p,c,i){return(+c&&((c*(1+i%2)%9)||9))+p},0)%10)}

```

Readable form:

```
function luhnCheck(ccNum) {
    return !(                                  // True if the result is zero.
             ccNum.split('').
               reverse().                      // Iterate over the string from rtl.
               reduce(function(prev, cur, idx) {
                 return prev +                 // Sum the results of each character.
                        (+cur &&               // If the current digit is 0, move on.
                         ((cur * (1 + idx % 2) // Double cur at even indices.
                           % 9) || 9));        // Sum the digits of the result.
               }, 0)
            % 10);                             // Is the sum evenly divisible by 10?
}

```
> 3 votes

# Answer
# JavaScript (ES6), 61 bytes

Sum of digits of `2*n` is `2*n` if `n in 0..4`, `2*n-9` if `n in 5..9`. That said, all the sum can be computed in one step.

```
s=>!([...s].reduceRight((t,d)=>t-d-i++%2*(d>4?d-9:d),i=0)%10)

```
> 3 votes

# Answer
# Powershell, 74 bytes

```
param($s)$s[$s.Length..0]|%{(1+$i++%2)*"$_"}|%{$r+=$_-9*($_-gt9)}
!($r%10)

```

## Explanation

1. for each char of an argument string, in reverse order
2. get a digit of double value of a digit
3. a double value of a digit can not be greater then 18. Therefore, we accumulate a value minus 9 if value \> 9
4. return true if the remainder of the division by 10 is 0

## Test script

```
$f = {

param($s)$s[$s.Length..0]|%{(1+$i++%2)*"$_"}|%{$r+=$_-9*($_-gt9)}
!($r%10)

}

@(
    ,("49927398716"      , $True)
    ,("49927398717"      , $False)
    ,("1234567812345670" , $True)
    ,("1234567812345678" , $False)
    ,("79927398710"      , $False)
    ,("79927398711"      , $False)
    ,("79927398712"      , $False)
    ,("79927398713"      , $True)
    ,("79927398714"      , $False)
    ,("79927398715"      , $False)
    ,("79927398716"      , $False)
    ,("79927398717"      , $False)
    ,("79927398718"      , $False)
    ,("79927398719"      , $False)
    ,("374652346956782346957823694857692364857368475368" , $True)
    ,("374652346956782346957823694857692364857387456834" , $False)
    ,("8" , $False)
    ,("0" , $True)
) | % {
    $s, $expected = $_
    $result = &$f $s
    "$($result-eq$expected): $result : $s"
}

```

## Output

```
True: True : 49927398716
True: False : 49927398717
True: True : 1234567812345670
True: False : 1234567812345678
True: False : 79927398710
True: False : 79927398711
True: False : 79927398712
True: True : 79927398713
True: False : 79927398714
True: False : 79927398715
True: False : 79927398716
True: False : 79927398717
True: False : 79927398718
True: False : 79927398719
True: True : 374652346956782346957823694857692364857368475368
True: False : 374652346956782346957823694857692364857387456834
True: False : 8
True: True : 0

```
> 3 votes

# Answer
# K (ngn/k), 26 bytes

```
{~10!+//10\(1+2!!#x)*.'|x}

```

Try it online!

Another k variant, with a major debt to @streetster's answer.
> 3 votes

# Answer
# GolfScript, 31 bytes

```
.,2%0\@{48-..4>+@!:a*++a}/;10%!

```

Try it online!

Golfscript pushes the input as a list of characters to the stack at the start of the program.

```
.                                Duplicate the top of the stack (input)
 ,2%                             Compute the modulo 2 of the length of the input,
                                 pushed 1/0 on the stack if the number if odd/even
    0                            Push an accumulater var on the stack, set to 0

     \                           Flip the even/odd and accumulator order on the stack
      @                          Bring the 3rd entry forward, input to the top

       {                }        Code block...
                         /       Apply the block of code to the elements of the list at
                                 the top of the stack. Each time through the loop, the
                                 next element from the list if pushed to the top of the
                                 stack
        48-                      Subtract "0" from the top of stack (which is a codepoint
                                 for the current digit/character)
           ..                    Duplicate the top of stack (the current digit) twice
             4>+                 If the current digit is >4 add one to the digit
                @                Pull the 3rd entry, the even/odd indicator, to the top
                 !:a             Flip the value and save in variable "a"
                    *            Multiple the top two stack entries, will be "0" or the
                                 value of current digit, with or without "1" more for the
                                 "+10" rule
                     ++          Add the current digit, to the possible "double" and
                                 "even/odd" bump
                       a         Push the flipped even/odd indicated to the top
                          ;      Drop the stop of stack, the even/odd indicator
                           10%   Find the modulo 10 of the accumulated digits
                              !  Invert the result

```

The only thing on the stack is the answer, which is printed by default
> 3 votes

# Answer
# Factor \+ `validators`, 5 bytes

```
luhn?

```

Try it online!
> 3 votes

# Answer
### Scala: 132

```
def q(x:Int)=x%10+x/10
def c(i:String)={val s=i.reverse
(s(0)-48)==10-(s.tail.sliding(2,2).map(n=>(q((n(0)-48)*2)+n(1)-48)).sum%10)}

```

invocation:

```
c("79927398713")

```
* reverse ("79927398713") = 31789372997
* s(0), s.tail: (3)(1789372997)
* sliding (2,2) = (17 89 37 29 97)
* map (q((n(0)-48\*2 + n(1)-48)) =\> q(('1'-'0')\*2)+ '7'-'0')=1\*2+7
> 2 votes

# Answer
# Haskell: 97

For some reason this isn't working for me, so here is my version

```
l=(\x->(==0)$(`mod`10).sum$zipWith($)(cycle[id,sum.map(read.(:"")).show.(*2)])(map(read.(:""))x))

```
> 2 votes

# Answer
# K4, 35 bytes

```
{~.*|$+/.:',/$x*1+1{y;~x}\|x:|.:'x}

```
> 2 votes

# Answer
# APL, 38 bytes

```
d←10∘⊥⍣¯1⋄{0=10|+/+/d x×1+~2|⍳⍴x←⌽d ⍵}

```

expects the number as a number, not a string, but that's only because tryAPL (understandably) doesn't implement

further reducible, i'm sure…
> 2 votes

# Answer
## Retina, ~~43~~ 42 bytes

Retina is (much) newer than this challenge.

```

;
r`(.);.
$1$&
\d
$*
1+
$.&
.
$*
$
$._
0$
```

The leading empty line is significant.

Prints `0` for falsy and `1` for truthy results.

Try it online! (Slightly modified to run all test cases at once.)

### Explanation

```

;
```

Insert `;` in every position to separate digits.

```
r`(.);.
$1$&

```

From the `r`ight, we repeatedly match two digits and double the left one. This way we avoid an expensive reversing of the list.

```
\d
$*

```

We match each digit and convert it to that many `1`s (that is, we convert each digit to unary).

```
1+
$.&

```

This matches each unary number and converts it back to decimal by replacing it with its length. Together with the previous stage, this adds the doubled digits.

```
.
$*

```

Again, we match every character and turn it into that many `1`s. That is we convert each digit individually back to unary. This also matches the `;` separators, which are treated as zeros in the conversion, which means they're simply removed. Since all the unary numbers are now squashed together we've automatically added the unary representations of the all digits together.

```
$
$._

```

At the end, we insert the length of the entire string, i.e. the decimal representation of the unary checksum.

```
0$

```

Finally we count the number of matches of this regex, i.e. we check whether the decimal representation ends in `0`, printing `0` or `1` accordingly.
> 2 votes

# Answer
# Jelly, 14 bytes

```
DUḤJḤ$¦DS$€S⁵ḍ

```

Try it online!

Explanation:

```
D              get digits
 U             reverse array
   JḤ$         for every other index,
  Ḥ   ¦        double the value
          €    for each value,
       D $     get the digits
        S$     and sum them
           S   sum the list
            ⁵ḍ check if it's divisible by 10

```
> 2 votes

# Answer
# Japt, ~~14~~ 13 bytes

Takes input as an array of digits.

```
ÔxÈ*ÒYu)ìxÃvA

```

Try it

```
ÔxÈ*ÒYu)ìxÃvA     :Implicit input of array
Ô                 :Reverse
 x                :Reduce by addition
  È               :After passing each element at 0-based index Y through the following function
   *              :   Multiply by
    Ò             :     Bitwise increment
     Yu           :     Y modulo 2
       )          :   End multiplication
        ì         :   Convert to digit array
         x        :   Reduce by addition
          Ã       :End function
           v      :Test for divisibility by
            A     :  10

```
> 2 votes

# Answer
# Pxem, 0 bytes (content) + 147 bytes (filename).

* Filename (escaped): `.w0.-.i.c\001.+.a\001.+.t.v.m.vQJ.z.v.m.v.c.m.+.c.t.-.m.v.t.v.m.-.m\001.+.!.c\011.x\011.-XX.a.t.v.s.m.v\001.-.t.v.m.v.c0.a\046.-.v.s@.w.t.c.c.Z.m\012.%.w.d.aY.o.d.A.m.+@.a`
* Content is empty.

Try it online!

## Usage

A single line that matches `^[0-9]+$`, ending with EOF, is given from stdin. A single `Y` is output if and only if truthy.

## Algorithm

1. Let l1 be a list storing each digit in reverse order.
2. Let s be 0.
3. Let l2 be an empty list.
4. If l1 is empty, go to step 9.
5. Pop one value from l1 and let it be n. Push n\*(s+1) onto l2.
6. If last value on l2 is more than 9, subtract 9 from it.
7. Let s be 1-s.
8. Go to step 4.
9. Calculate (sum of each item in l2)%10.
10. If step 9 resulted in 0, the program returns truthy; otherwise falsey.

## With comments

```
# getchar() unil EOF
# substract 48 for each character
.w0.-.i.c\001.+.aXX.z
# at this point stack is -1, [0-9], ..., [0-9], 48.
# add 1 to -1 so: 0, ..., 48.
# move 0 to bottom: [0-9], ..., 48, 0.
.a\001.+.t.v.m.vXX.z
# loop
# every time loop begins, bottom should be [01].
# also heap should be same as bottom.
.aQJ.zXX.z
  # to: [0-9], [01], ..., 48, ..., [01]... I think
  # WTF did I do here?
  .a.v.m.v.c.m.+.c.t.-.m.v.t.v.m.-.mXX.z
  # multiply [0-9] to ([01]+1)
  .a\001.+.!XX.z
  # subtract 9 if more than 9
  .a.c\011.x\011.-XX.aXX.z
  # move top to bottom, replacing it
  .a.t.v.s.m.vXX.z
  # alt for [01] xor 1; subtract from 1
  # then move to bottom
  .a\001.-.t.v.m.vXX.z
# break if top equals 48
.a.c0.aXX.z
# make 48 to 10, then remove botton [01]
# OBTW reversed, but whatever
.a\046.-.v.sXX.z
# loop
.a@.wXX.z
  # if size is 1; then
  .a.t.c.c.ZXX.z
    # modulo by 10
    .a.m\012.%XX.z
    # if it is 0; then print Y and exit; else exit; fi
    .a.w.d.aY.o.d.AXX.z
  # fi; push (pop+pop)
  .a.m.+
# end of loop
.a@.a

```
> 2 votes

# Answer
# Vyxal, ~~<sup>12</sup>~~ 11 bytes

*-1 byte thanks to @lyxal reminding me about multibyte lambdas.*

```
ṘÞTf‡d∑ẇ∑₀Ḋ

```

Try it Online!

Explanation:

```
             # Implicit input
Ṙ            # Reverse
 ÞT          # Transpose
   f         # Flatten list
    ‡  ẇ     # For every second element:
     d       #   Double
      ∑      #   Sum digits
        ∑    # Sum all elements
         ₀Ḋ  # x % 10 == 0?
             # Implicit output

```
> 2 votes

# Answer
# Julia 1.0, ~~51~~ 50 bytes

```
~=digits;!n=(k=~n;k[2:2:end]*=2;sum(sum,.~k)%10<1)

```

Try it online!
> 2 votes

# Answer
# GNU sed, 140 bytes

(including +1 for the `-r` flag)

```
s/^(..)*.$/0&/
s/(.)./\1x&/g
s/x[5-9]/1&/g
s/[0x]//g
s/[789]/&6/g
s/[456]/&3/g
s/[369]/&11/g
s/[258]/&1/g
s/.{10}//g
s/.+/false/
s/^$/true/

```

Sed is almost never the most natural language for arithmetic, but here we go:

```
#!/bin/sed -rf

# zero-pad to even length
s/^(..)*.$/0&/
# double every other digit
s/(.)./\1x&/g
# add carry (converts mod-9 to mod-10)
s/x[5-9]/1&/g
# convert sum to unary
s/[0x]//g
s/[789]/&6/g
s/[456]/&3/g
s/[369]/&11/g
s/[258]/&1/g
# remove whole tens
s/.{10}//g
# output 'true' or false
s/.+/false/
s/^$/true/

```
> 1 votes

# Answer
## PHP - 136 characters

```
function t($c){foreach($a=str_split(strrev($c)) as $k=>&$v){$v=array_sum(str_split(($k % 2)!==0?2*$v:$v));}return !(array_sum($a)% 10);}

```
> 1 votes

# Answer
# MATL, ~~23~~ 20 bytes (non competing)

```
P!Utn:2X\!*t9>+s10\~

```

Try it online!

Outputs 1 for a valid number, 0 otherwise.

Saved three bytes thanks to Luis Mendo's suggestions.

## Explanation

```
P       % flip the order of elements
!       % transpose into column vector
U       % convert char matrix to numeric
t       % duplicate the vector
n       % find the length
:       % create a new vector length n (1, 2, 3, ... n)
2       % number literal
X\      % take it mod 2, to make the new vector (1, 2, 1, ..., (n-1) mod 2 +1)
!       % transpose
*       % element-wise product
t       % duplicate
9       % push 9
>       % 1 if it is greater than 9
+       % add the vectors, this makes the last digit of each the same as the sum of the digits
s       % add them
10      % number literal
\       % mod 10
~       % logical 'not' (element-wise)
        % (implicit) convert to string and display

```
> 1 votes

# Answer
# K (oK), 28 bytes

**Solution:**

```
~10!+/48!,/$(1+2!!#x)*48!|x:

```

Try it online!

**Examples:**

```
~10!+/48!,/$(1+2!!#x)*48!|x:"1234567812345670"
1
~10!+/48!,/$(1+2!!#x)*48!|x:"1234567812345678"
0

```

**Explanation:**

```
~10!+/48!,/$(1+2!!#x)*48!|x: / the solution
                          x: / save input as variable x
                         |   / reverse it
                      48!    / mod with 48 (converts ascii -> int)
            (       )*       / multiply with stuff in brackets
                  #x         / length of x
                 !           / til, the range 0..x-1
               2!            / mod with 2 (0 1 2 3 -> 0 1 0 1)
             1+              / add 1 (0 1 0 1 -> 1 2 1 2)
           $                 / convert to string
         ,/                  / flatten string
      48!                    / convert this into integers
    +/                       / sum over the list
 10!                         / modulo 10
~                            / negate (so 1 for truthy, 0 for falsy)

```

**Extra:**

A couple of 30-byte solutions in **K4**, not quite as short...

```
~.*|$+/,/10\:'((#x)#1 2)*.:'x:
~.*|$+/.:'',/$((#x)#1 2)*.:'x:

```
> 1 votes

# Answer
# Pyt, 20 bytes

```
ĐḶ⌊⁺⇹ą↔⇹ř⁻2%⁺*ŚƩ1ᴇ%¬

```

Explanation:

```
                        Implicit input
Đ                       Duplicate input
 Ḷ⌊⁺                    Get length of integer in base-10 (floor(log_10(input))+1)
    ⇹                   Swap top two on stack
     ą↔                 Convert input to an array of digits, and reverse
       ⇹                Swap top two on stack
        ř⁻              Push [0,1,2,...,floor(log_10(input))]
          2%            Take previous array element-wise mod 2
            ⁺           Increment each element of the array
             *          Elementwise multiplication of the arrays
              Ś         Elementwise sum of digits
               Ʃ        Sum up array
                1ᴇ%     Mod 10
                   ¬    Negate (this returns false if not 0, and true otherwise)

```

Try it online!
> 1 votes

# Answer
# Kotlin, 77 bytes

```
mapIndexed{i,c->(""+(2-(length%2 xor i%2))*(c-'0')).sumBy{it-'0'}}.sum()%10<1

```

## Beautified

```
mapIndexed { i, c ->
    ("" + (2 - (length % 2 xor i % 2)) * (c - '0')).sumBy { it - '0' }
}.sum() % 10 < 1

```

## Test

```
data class Test(val input: String, val output: Boolean)

val tests = listOf(
        Test("49927398716", true),
        Test("49927398717", false),
        Test("1234567812345670", true),
        Test("1234567812345678", false),
        Test("79927398710", false),
        Test("79927398711", false),
        Test("79927398712", false),
        Test("79927398713", true),
        Test("79927398714", false),
        Test("79927398715", false),
        Test("79927398716", false),
        Test("79927398717", false),
        Test("79927398718", false),
        Test("79927398719", false),
        Test("374652346956782346957823694857692364857368475368", true),
        Test("374652346956782346957823694857692364857387456834", false),
        Test("8", false),
        Test("0", true)
)

fun String.f() =
mapIndexed{i,c->(""+(2-(length%2 xor i%2))*(c-'0')).sumBy{it-'0'}}.sum()%10<1
fun main(args: Array<String>) {
    for ((input, expectedOut) in tests) {
        val actualOut = input.f()
        if (actualOut != expectedOut) {
            System.err.println("$input $expectedOut $actualOut")
        }
    }
}

```

## TIO

TryItOnline
> 1 votes

# Answer
# Dart, 120 bytes

```
f(s,{i=0})=>s.split('').reversed.map(int.parse).map((n)=>i++%2>0?n*2:n).map((n)=>n>9?n-10+1:n).fold(0,(p,e)=>p+e)%10==0;

```

Try it online!
> 1 votes

# Answer
# Perl 6, 37 bytes

```
(*.flip.comb >>*>>[1,2]).comb.sum%%10

```

Try it online!

A Whatever lambda that takes a number and returns a boolean.

### Explanation:

```
 *.flip                  # Reverse the number
       .comb             # Split to list of digits
             >>*>>       # Multiply each element by:
                  [1,2]  # The list 1,2,1,2,1,2...
(                      ).comb           # Split the list to a list of digits
                             .sum       # Get the digit sum
                                 %%10   # Return if it is divisible by 10

```
> 1 votes

# Answer
**Julia, 67 bytes**

```
x=digits(n)
sum(x[1:2:end])+sum(reduce(vcat,digits.(x[2:2:end]*2)))

```
> 1 votes

# Answer
# MathGolf, 11 bytes

```
▒xôï¥)*Σ+♂÷

```

Try it online!

At least I tied with Jelly, I can't really see a way to remove a byte from this.

## Explanation

```
▒             split to list of chars/digits
 x            reverse int/array/string
  ô           start block of length 6 (for-each)
   ï          index of current loop
    ¥         modulo 2
     )        increment
      *       pop a, b : push(a*b)
       Σ      digit sum
        +     add to the counter (implicitly calculates 0+x when stack only has one element)
              Block ends here
         ♂    push 10
          ÷   is divisible

```
> 1 votes

# Answer
# Haskell, 73 bytes

```
i#0=0
i#n|m<-mod n 10=i*(m+sum[-9|m>4])+m+(1-i)#div n 10
f n=mod(0#n)10<1

```

Try it online!
> 1 votes

# Answer
# APL(NARS), 37 chars, 74 bytes

```
{0=10∣+/{+/10 10⊤⍵}¨v+v×0=2∣⍳≢v←⌽⍎¨⍵}

```

test:

```
  f←{0=10∣+/{+/10 10⊤⍵}¨v+v×0=2∣⍳≢v←⌽⍎¨⍵}
  f '1234567812345670'
1
  f '49927398717'
0
  f '1234567812345678'
0
  f '79927398710'
0
  f '79927398719'
0
  f '374652346956782346957823694857692364857368475368'
1
  f '374652346956782346957823694857692364857387456834'
0
  f ,'8'
0
  f ,'0'
1

```

comment:

```
{0=10∣+/{+/10 10⊤⍵}¨v+v×0=2∣⍳≢v←⌽⍎¨⍵}
                                ⍎¨⍵ for each element of ⍵ (that would be char digits) convert in int
                             v←⌽    reverse the array result of above, and assign it to variable v
                           ⍳≢        produce all index of above v that are 1..≢v
                        0=2∣         produce one array of boolean where 0 means even index, 1 odd
                    v+v×            multipy that array for v itself (means get only odd ones the other 0)
                                    and sum it to v (so we have v with elements index odd duplicate)
       {+/10 10⊤⍵}¨                convert each element of the array of 2 digits base 10 than sum
   10∣+/                            sum all element mod 10
 0=                                if result is 0 return 1 (true), else return 0 (false)

```
> 1 votes

# Answer
# PHP, ~~83~~ 82 bytes

```
foreach(str_split(strrev($argn))as$x=>$d)$m+=$d+($d%10+$d/5|0)*$x&=1;echo!($m%10);

```

As standalone program, call with `php -F`. Input is `STDIN`, output is to `STDOUT` as bool (1 or empty).

```
$ echo 49927398716|php -F luhn.php
1

$ echo 49927398717|php -F luhn.php

$ echo 1234567812345670|php -F luhn.php
1

```

Verify all test cases
> 1 votes

# Answer
# Japt v2.0a0, 14 bytes

```
¬ÔxÈ*ÒYu)ìxÃvA

```

The first byte can be removed if I took input as array of chars.

Try it

```
¬                   //Split (implicit) input into list of chars
 Ô                  //Reverse
  xÈ                //Get the sum of every char after passing through the following function
    *               //  Multiply the element
     ÒYu)           //  By the index modulus 2 plus 1 (Odd -> 2, Even -> 2)
         ìx         //  And take the sum of the digits
  Ã                 //Close function
vA                  //And check if result is divisible by 10

```
> 1 votes

# Answer
# , 46 bytes

```
function(x,y=rev(x)*1:2)!sum(y%%10+y%/%10)%%10

```

Try it online!
> 1 votes

# Answer
# Husk, ~~15~~ 13 bytes

*Edit: -2 bytes thanks to Razetime*

```
¬→dṁΣzod*¢ḣ2↔

```

Try it online!

```
¬                   # logical NOT of
 →d                 # last decimal digit of
   ṁΣ               # sum of sums of results of
     z              # zipping two lists together
         ¢ḣ2        # list 1: [1,2] repeated
            ↔       # list 2: input, reversed
      o             # using these two functions:
       d*           # decimal digits of product

```
> 1 votes

# Answer
# Zsh, 52 bytes

```
for j (${(Oas::)1})((s+=++i%2?j:j*2.2%10))
<<<$s[-1]

```

Try it Online..

Parse input into array and reverse it: `${(Oas::)1}`. Then iterate over the array elements.
`0` is `truthy`, non-zero is `falsy`.

<sub>From my work, the Visa test number (`4111 1111 1111 1111`) is embedded in my brain.</sub>

<sub>Previous efforts: ~~55 bytes~~ ~~61 bytes~~ ~~72 bytes~~ ~~77 bytes~~</sub>
> 1 votes

# Answer
# dc, 61 bytes

```
[A~rdZ1<S]dsSxz2%1=0[2*SaSaz1<LLaLalSx]dsLx[+z1<L]dsLxA%0=0zp

```

Try it online!

```
[A~rdZ1<S]dsSx # split: take quotient and remainder by 10, rotate quotient to top
z2%1=0 # if odd length, prepend 0 (I think. I poked it until it worked)
[2*SaSaz1<LLaLalSx]dsLx # double every other number, split them all
[+z1<L]dsLx # sum everything
A%0=0zp # if n%10 == 0, print 1; else, print 0

```

The last line works because:

1. Each register holds 0 by default
2. Comparisons attempt to execute whatever's in the specified register (`0` here)
3. Executing a number simply returns the number

So if we execute the contents of register `0`, then we have one item on the stack: 0. Otherwise, the stack is empty. Use `z` to convert this to a 0 or 1.
> 1 votes

# Answer
## C (gcc), ~~126~~ 110 bytes

*-16 bytes thanks to ceilingcat*

```
#define e s[1][i]
c,b;main(i,s)char**s;{for(i=strlen(s[1]);i--;b+=e-=e/10?9:0)e-=48,e*=c++%2+1;return!(b%10);}

```

Input is taken through an argument and output uses exit codes, 0 for false and 1 for true

Explanation:

```
#define e s[1][i]
c,b;
main(i,s) // i, c, and b are ints for program use
char**s; // argv, used for input
{
    for(i=strlen(s[1]); i--; b+=e-=e/10?9:0) // iterate backwards through string, and add to the total (b) while also doing the digit add
        e-=48, // subtract '0'
        e*=c++%2+1; // double each odd index
    return!(b%10); // check if b ends in 0 and return that
}

```
> 1 votes

# Answer
# Vyxal, 16 bytes

```
₀τƛ¥₂ßd&›₀τ∑;∑₀Ḋ

```

Try it Online!

```
₀τ               # Digits...
  ƛ         ;    # Map
   ¥₂            # If register is even
     ßd          # Double
       &›        # Increment register
         ₀τ      # Digits...
           ∑     # Sum
             ∑   # Sum of all...
              ₀Ḋ # is divisible by 10?

```
> 1 votes

# Answer
# Fig, \\$10\log\_{256}(96)\approx\\$ 8.231 bytes

```
]SeSn2@h$f

```

Try it online!

Outputs using inverted logic: positive integer for falsey, 0 for truthy

```
]SeSn2@h$f
         f # Digits of number
        $  # Reverse
    n2@    # For every other item in the list
       h   # Unhalve (double)
  eS       # Digit sum of each
 S         # Sum
]          # Take the last digit (equivalent to mod 10)

```
> 1 votes

# Answer
# Vyxal, 8 bytes

```
fṘ⁽dẇṠ∑t

```

Try it Online!

Outputs 0 for truthy, any positive integer for falsey.

## Explained

```
fṘ⁽dẇṠ∑t
fṘ       # reverse the list of digits of the input
  ⁽dẇ    # double each odd-indexed digit
     Ṡ∑t # sum each number, and take the tail of the sum

```
> 1 votes

# Answer
# \>\<\>, ~~39~~ 37 bytes

```
00@:}2%1+$c%*:a%$9)++{1+$1l3=.
n;a%0=

```

Try it online

**Explanation**

```
00                                 # init sum and counter to 0
  @:}2%1+                          # set counter to 1 if even and 2 if odd
         $c%*                      # mod current number by 12 and multiply by counter
               :a%$9)++            # sum digits and add to total sum
                       {1+$        # increment counter
                           1l3=.   # jump to next row if done, else skip init on 1st row
n;a%0=                             # print sum mod 10 == 0

```
> 1 votes

# Answer
# Thunno 2 `t!`, 8 bytes

```
drŻɗ⁺×ʂS

```

Attempt This Online!

#### Or 10 bytes flagless:

```
drŻɗ⁺×ʂSt~

```

Attempt This Online!

#### Explanation

```
drŻɗ⁺×ʂSt~  # Implicit input
dr          # Cast to digits; reverse the list
  Ż         # Without popping, push [0..length)
   ɗ⁺       # Mod 2 of each; increment each
     ×      # Multiply elementwise
      ʂ     # Sum the digits of each number
       S    # Sum the resulting list
        t   # Pop and push the last digit
         ~  # And check if this equals 0
            # Implicit output

```
> 1 votes

# Answer
# Pyth, 19 bytes (non-competing)

Non-competing since Pyth is newer than this challenge.

```
!%s.esj*b@S2kT_jQTT

```

A program that takes input of a string on STDIN and prints `True` or `False` as appropriate.

Try it online or verify all test cases

**How it works**

```
!%s.esj*b@S2kT_jQTT  Program. Input: Q
               jQT   Yield the base-10 representation of Q as a list, giving the digits
              _      Reverse
   .e                Enumerated map, with elements as b and indices as k:
          S2           Yield [1, 2]
         @  k          Modular indexing with k, yielding 1 for even indices and 2 for odd
                       indices
       *b              Multiply by b
      j      T         Yield the digits
     s                 Sum
  s                  Sum the resulting list
 %                T  Modulo 10
!                    Logical not, yielding True for 0 and False otherwise
                     Implicitly print

```
> 0 votes

# Answer
# Tcl, 85 bytes

```
proc L n {expr ([regsub -all . [string rev $n] {+([incr i]%2?&:&*2%10+(&>4))}])%10<1}

```

Try it online!

~~Tcl, 86 bytes
```
proc L n {expr !(([regsub -all . [string rev $n] {+([incr i]%2?&:&*2%10+(&>4))}])%10)}

```
Try it online!<br>Tcl, 119 bytes
```
proc L n {expr !(([join [lmap a [lreverse [split $n ""]] {expr [incr i]%2?$a:[join [split [expr 2*$a] ""] +]}] +])%10)}

```
Try it online!<br>~~
> 0 votes

# Answer
# bash, ~~109~~ ~~106~~ ~~90~~ 71 bytes

Output of `0` means `True`. Anything else means `False`.

```
for x in `rev<<<$1|fold -1`;{((s+=++i%2?x:(x*22/10)%10));}
echo $[s%10]

```

Try it online! ~~<sub>90bytes</sub>~~ ~~<sub>Alt-90bytes-backwards</sub>~~
> 0 votes

# Answer
# Burlesque, 33 bytes

```
riXX<-J2ENj2en2?***{XX++}ms10.%z?

```

Try it online!

```
ri         # Read input as int
XX         # Explode into digits
<-         # Reverse
J2EN       # Duplicate and take every 2nd starting from 1
j2en       # Take the other half
2?*        # Multiply each digit by 2
**         # Remerge arrays
{XX++}ms   # Sum the digits of multidigit and then sum result
10.%z?     # If result `mod` 10 is 0

```
> 0 votes

# Answer
# Ruby, ~~67~~ 66 bytes

-1 byte thanks to south

```
->n{n.digits.each_slice(2).map{_1+(2.*_2||0).digits.sum}.sum%10<1}

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, arithmetic, checksum
---


title: Golf the xᵗʰ root of x

text:
# Question
Title: Golf the xᵗʰ root of x
While bored in high-school (when I was half my current age...), I found that \\$f(x) = x^{x^{-1}}\\$ had some interesting properties, including e.g. that the maximum \\$f\\$ for \\$0 ≤ x\\$ is \\$f(e)\\$, and that the binding energy per nucleon of an isotope can be approximated as \\$6 × f(x ÷ 21)\\$...

Anyway, write the shortest function or program that calculates the xth root of x for any number in your language's domain.

## Examples cases

### For all languages

```
     -1   >       -1
   ¯0.2   >    -3125
   ¯0.5   >        4
    0.5   >     0.25
      1   >        1
      2   >    1.414
      e   >    1.444
      3   >    1.442
    100   >    1.047
  10000   >    1.001

```

### For languages that handle complex numbers

```
   -2   >        -0.7071i
    i   >            4.81
   2i   >    2.063-0.745i
 1+2i   >   1.820-0.1834i
 2+2i   >   1.575-0.1003i

```

### For languages that handle infinities

```
-1/∞   >   0    (or ∞ or ̃∞)
   0   >   0    (or 1 or ∞)
 1/∞   >   0
   ∞   >   1
  -∞   >   1

```

### For languages that handle both infinities and complex numbers

```
 -∞-2i   >   1      (or ̃∞)

```

---

 `̃∞` denotes directed infinity.

# Answer
# TI-BASIC, 3 bytes

```
Ans×√Ans

```

TI-BASIC uses tokens, so `Ans` and `×√` are both one byte.

### Explanation

`Ans` is the easiest way to give input; it is the result of the last expression. `×√` is a function for the x'th root of x, so for example `5×√32` is 2.
> 39 votes

# Answer
# Jelly, 2 bytes

Try it online!

### How it works

```
*İ    Main link. Input: n

 İ    Inverse; yield 1÷n.
*     Power (fork); compute n ** (1÷n).

```
> 24 votes

# Answer
# Javascript (ES2016), 11 bytes

```
x=>x**(1/x)

```

I rarely ever use ES7 over ES6.
> 16 votes

# Answer
## Python 3, 17 bytes

```
lambda x:x**(1/x)

```

Self-explanatory
> 15 votes

# Answer
# J, 2 bytes

```
^%

```

Try it online!.

### How it works

```
^%  Monadic verb. Argument: y

 %  Inverse; yield 1÷y.
^   Power (hook); compute y ** (1÷y).

```
> 11 votes

# Answer
# Haskell, ~~12~~ 11 bytes

Thanks @LambdaFairy for doing some magic:

```
(**)<*>(1/)

```

My old version:

```
\x->x**(1/x)

```
> 11 votes

# Answer
## Pyth, 3 bytes

```
@QQ

```

Trivial challenge, trivial solution...

### (noncompeting, 1 byte)

```
@

```

This uses the implicit input feature present in a version of Pyth that postdates this challenge.
> 9 votes

# Answer
# JavaScript ES6, 18 bytes

```
n=>Math.pow(n,1/n)

```
> 8 votes

# Answer
## Java 8, 18 bytes

```
n->Math.pow(n,1/n)

```

Java isn't in last place?!?!

Test with the following:

```
import java.lang.Math;

public class Main {
  public static void main (String[] args) {
    Test test = n->Math.pow(n,1/n);
    System.out.println(test.xthRoot(6.0));
  }
}

interface Test {
  double xthRoot(double x);
}

```
> 8 votes

# Answer
# Mathematica, ~~8~~ ~~7~~ ~~4~~ 7 bytes

```
#^#^-1&

```

~~More builtin-only answers, and now even shorter!~~ Nope. ~~By definition, the next answer should be 13 bytes. (Fibonacci!)~~ The pattern is still broken. :(
> 6 votes

# Answer
# R, ~~19~~ 17 bytes

```
function(x)x^x^-1

```

-2 bytes thanks to @Flounderer
> 6 votes

# Answer
# MATL, 5 bytes

```
t-1^^

```

**Try it online!**

```
t       % implicit input x, duplicate
 -1     % push -1
   ^    % power (raise x to -1): gives 1/x
    ^   % power (raise x to 1/x). Implicit display

```
> 6 votes

# Answer
# Java, 41 bytes

```
float f(float n){return Math.pow(n,1/n);}

```

Not exactly competitive because Java, but why not?
> 6 votes

# Answer
# CJam, 6 bytes

```
rd_W##

```

Try it online!

### How it works

```
rd     e# Read a double D from STDIN and push it on the stack.
  _    e# Push a copy of D.
   W   e# Push -1.
    #  e# Compute D ** -1.
     # e# Compute D ** (D ** -1).

```
> 5 votes

# Answer
# Perl 5, 10 bytes

9 bytes plus 1 for `-p`

```
$_**=1/$_

```
> 5 votes

# Answer
# NARS APL, 2 bytes

```
√⍨

```

NARS supports the  function, which gives the ⍺-th root of ⍵. Applying commute (⍨) gives a function that, when used monadically, applies its argument to both sides of the given function. Therefore `√⍨ x``x √ x`.

### Other APLs, 3 bytes

```
⊢*÷

```

This is a function train, i.e. `(F G H) x``(F x) G H x`. Monadic  is identity, dyadic `*` is power, and monadic `÷` is inverse. Therefore, `⊢*÷` is *x* raised to 1/*x*.
> 5 votes

# Answer
# Ruby, 15 Bytes

```
a=->n{n**n**-1}

```

Ungolfed:

`->` is the *stabby* lambda operator where `a=->n` is equivalent to `a = lambda {|n|}`
> 5 votes

# Answer
# Python 2 - 56 bytes

The first actual answer, if I'm correct. Uses Newton's method.

```
n=x=input();exec"x-=(x**n-n)/(1.*n*x**-~n);"*999;print x

```
> 5 votes

# Answer
# dc, 125 bytes

```
15k?ddsk1-A 5^*sw1sn0[A 5^ln+_1^+ln1+dsnlw!<y]syr1<y1lk/*sz[si1[li*li1-dsi0<p]spli0<p]so0dsw[lzlw^lwlox/+lw1+dswA 2^!<b]dsbxp

```

Unlike the other dc answer, this works for *all* real \\$x\\$ greater than or equal to \\$1 (\\$1 ≤ x$). Accurate to 4-5 places after the decimal.

I would have included a TIO link here, but for some reason this throws a segmentation fault with the version there (`dc 1.3`) whereas it does *not* with my local version (`dc 1.3.95`).

### Explanation

As **dc** does not support raising numbers to non-integer exponents to calculate \\$x^\frac1x\\$, this takes advantage of the fact that:

$$x^\frac1x = e^\frac{\ln x}x$$

So, to calculate \\$\ln(x)\\$, this also takes advantage of the fact that:

$$\int \frac1x dx = \ln(x) + c$$

whose definite integral from \\$1\\$ to \\$b = x\\$ is numerically-approximated in increments of \\$10^{-5}\\$ using the following summation formula:

$$\int\_1^b \frac1x dx = \sum\_{i=1}^{10^{5}(b-1)} \frac 1 {10^5 + i}$$

The resulting sum is then multiplied by \\$\frac1x\\$ to get \\$\frac{\ln(x)}x\\$. \\$e^{\frac{\ln(x)}x}\\$ is then finally calculated using the \\$e^x\\$ Maclaurin Series to 100 terms as follows:

$$e^x=\sum^{10^2}\_{n=0}\frac{x^n}{n!}$$

This results in our relatively accurate output of \\$x^\frac1x\\$.
> 5 votes

# Answer
## Seriously, 5 bytes

```
,;ì@^

```

Try it online!

Explanation:

```
,;ì@^
,;     input, dupe
  ì@   1/x, swap
    ^  pow

```
> 4 votes

# Answer
# , 5 chars / 7 bytes

```
Мű⁽ïï

```

`Try it here (Firefox only).`

Trivial.
> 4 votes

# Answer
## Pyke (commit 29), 6 bytes

```
D1_R^^

```

Explanation:

```
D      - duplicate top
 1_    - load -1
   R   - rotate
    ^  - ^**^
     ^ - ^**^

```
> 4 votes

# Answer
# Pylons, 5 bytes.

```
ideAe

```

How it works.

```
i # Get command line input.
d # Duplicate the top of the stack.
e # Raise the top of the stack to the power of the  second to the top element of the stack.
A # Push -1 to the stack (pre initialized variable).
e # Raise the top of the stack to the power of the second to the top element of the stack.
  # Implicitly print the stack.

```
> 4 votes

# Answer
# Japt, 3 bytes

```
UqU

```

Test it online!

Very simple: `U` is the input integer, and `q` is the root function on numbers.
> 4 votes

# Answer
## C++, 48 bytes

```
#include<math.h>
[](auto x){return pow(x,1./x);}

```

The second line defines an anonymous lambda function. It can be used by assigning it to a function pointer and calling it, or just calling it directly.

Try it online
> 4 votes

# Answer
## C, 23 bytes

```
#define p(a)pow(a,1./a)

```

This defines a macro function `p` which evaluates to the `a`th root of `a`.

Thanks to Dennis for reminding me that `gcc` doesn't require `math.h` to be included.

Thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ for reminding me that the space after the first `)` is not needed.

Try it online
> 4 votes

# Answer
# Milky Way 1.6.5, 5 bytes

```
'1'/h

```

---

### Explanation

```
'      ` Push input
 1     ` Push the integer literal
  '    ` Push input
   /   ` Divide the STOS by the TOS
    h  ` Push the STOS to the power of the TOS

```

> x\**(1/x)

---

### Usage

```
$ ./mw <path-to-code> -i <input-integer>

```
> 4 votes

# Answer
## , 6 bytes

```
j.1\/^

```

No online link because the online IDE doesn't work (specifically, exponentiation is broken)

Explanation:

```
j.1\/^
j.      push two copies of input
  1\/   push 1/input (always float division)
     ^  push pow(input, 1/input)

```
> 4 votes

# Answer
# C# - ~~18~~ ~~43~~ 41 bytes

```
float a(float x){return Math.Pow(x,1/x);}

```

-2 byes thanks to @VoteToClose

Try it out

Note:

> First actual attempt at golfing - I know I could do this better.
> 4 votes

# Answer
# PARI/GP, 9 bytes

```
x->x^x^-1

```

This is shorter than the alternatives `x->x^(1/x)` and `x->sqrtn(x,x)`. It uses the right-associativity of `^` and the strong binding of the unary `-`. GP isn't quite functional enough to curry `(a,b)->sqrtn(a,b)` into `(x)->sqrtn(x,x)`; the best it can manage is `x->call(sqrtn,[x,x])` which is far too long.
> 3 votes

# Answer
# PHP 5.6, ~~32~~ ~~30~~ 29 bytes

```
function($x){echo$x**(1/$x);}

```

or

```
function($x){echo$x**$x**-1;}

```

30-\>29, thank you Dennis!
> 3 votes

# Answer
# Awk, 8 bytes

```
$1^$1^-1

```

A shell command to check it

```
awk '{print $1^$1^-1}'

```

---

Longer version (+1) with

```
$1^(1/$1)

```
> 3 votes

# Answer
# MATLAB, 11bytes

```
@(x)x^(1/x)

```

Creates an anonymous function. This will work with all test cases including complex numbers and infinities.

This also works with **Octave**. You can try online here. Simply enter something like:

```
f=@(x)x^(1/x)

```

At the command line of the online interpreter, then do:

```
f(-1)

```

To test.
> 3 votes

# Answer
# C#, 25 bytes, type: `double`

Bare form of a lambda expression:

```
x=>System.Math.Pow(x,1/x)

```

The expression can be assigned to a function variable, e.g. (`Func<double, double>`), ...

`System.` can be omitted, if `using System;` is used (but more bytes).

Complete **test program (143 bytes)** with the input of the question:

```
using System;class P{static void Main(){Array.ForEach(new double[]{-.2,-.5,.5,1,2,Math.E,3,100,10000},x=>Console.WriteLine(Math.Pow(x,1/x)));}}

```

**Result:**

```
-3125
4
0,25
1
1,4142135623731
1,44466786100977
1,44224957030741
1,0471285480509
1,0009214583193

```

# C#, 37 bytes, type: `Complex`

```
x=>System.Numerics.Complex.Pow(x,1/x)

```

Also the assembly for `System.Numerics` needs to be referenced. The division operator is overloaded for complex arguments.

**Test program (189 bytes)** with the input of the question for complex numbers:

```
using System;using C=System.Numerics.Complex;class P{static void Main(){Array.ForEach(new C[]{new C(-2,0),new C(0,1),new C(0,2),new C(1,2),new C(2,2)},x=>Console.WriteLine(C.Pow(x,1/x)));}}

```

**Result:**

```
(4,32963728535968E-17, -0,707106781186548)
(4,81047738096535, 0)
(2,0628722350809, -0,745007062179724)
(1,81984053615444, -0,183434723804562)
(1,57500291115344, -0,100274868564155)

```

**Test program (264 bytes)** with infinity:

```
using System;using C=System.Numerics.Complex;class P{static void Main(){var p=double.PositiveInfinity;var n=double.NegativeInfinity;Array.ForEach(new C[]{new C(-1/p,0),new C(0,0),new C(1/p,0),new C(p,0),new C(n,0),new C(n,2) },x=>Console.WriteLine(C.Pow(x,1/x)));}}

```

**Result:**

```
(0, 0)
(0, 0)
(0, 0)
(1, 0)
(1, 0)
(1, 0)

```
> 3 votes

# Answer
# Vitsy, 4 + 1 (function declaration) = 5 bytes

Hey, look, my language actually does this. Go figure.

```
Di^^
D    Duplicate the top item (input)
 i   Push -1.
  ^  Pop top (-1), put the second to top to the power of the popped item (x^-1)
   ^ Same as above, except we now have the desired number.
```

This is a function that leaves the value requested on the stack. For view-ability, I have also made the program output on the Try it Online! link.

Try it Online!
> 3 votes

# Answer
# Bean, 11 bytes

Hexdump:

```
00000000 26 4c a0 43 95 4c a5 3a 8e 20 43  &L C.L¥:. C
0000000b

```

Equivalent JavaScript:

```
A**(1/A)

```

Implicitly converts first line of input to number as `A` and implicitly outputs the result of the expression.

### Try the demo here.

### Try the test suite here.
> 3 votes

# Answer
# Codename Dragon, 16 bytes

```
a=<>;dispa^(1/a)

```

I'm abusing the lack of a syntax error.

Ungolfed:

```
disp((a=<>)^(1/a))

```

This is a simple program that takes input through `<>`.

You can find an interpreter here, no github site yet.
> 2 votes

# Answer
# Jolf, 5 bytes

Try it here!

```
^j/1j
 j    input
^ /1j to the 1/j pow.

```
> 2 votes

# Answer
## Gnuplot, 13 bytes

```
f(x)=x**(1/x)

```

or

```
f(x)=x**x**-1

```
> 2 votes

# Answer
# Racket, 28 22 bytes

```
(λ(n)(expt n(/ 1 n)))

```

@cat gets credit for the 6 byte save. Thanks!

Seriously, Racket is impossible to golf with :). Nothing to see here, move along!
> 2 votes

# Answer
# Factor, ~~14~~ 10 bytes

```
1 over / ^

```

Expects input on top of the stack.
> 2 votes

# Answer
## Convex, 3 bytes

Convex is a new language that I am developing that is heavily based on CJam and Golfscript. The interpreter and IDE can be found here. Input is an integer into the command line arguments. Indexes are one-based. Uses the CP-1252 encoding. This answer in non-competing as it was created after this challenge.

```
_¹#

```

Explanation:

```
    Implied input
_   Duplicate top of stack
 ¹  Find reciprocal
  # Power
    Implied output

```
> 2 votes

# Answer
# Brachylog, ~~8~~ 7 bytes

Thanks to Fatalize for saving a byte.

```
^?^-1=.

```

## Explanation

```
^?^-1=.
     =.   unify output with
^?^-1     input raised to the 1/input power

```
> 2 votes

# Answer
# Lua, 20

```
n=(...)print(n^n^-1)

```

How it works:

```
n=(...)              Take input and store at n
       print(
             n^n^-1  n^(n^(-1))
                   )

```
> 2 votes

# Answer
# Quetzalcoatl, 4 bytes

```
c.I?

```

Explanation:

```
c    # Input
 .   # Duplicate
  I  # Inverse
   ? # Power

```
> 2 votes

# Answer
# dc, ~~8~~ 6 chars

Outputs to the top of the stack:

```
?d1r/^

```

Or if I can expect the input at the top of the stack, this 5 char solution works too:

```
d1r/^

```

Explanation:

```
?        take input from STDIN and execute it (numbers are executed by pushing to the stack)
 d1r     duplicate top of stack, push 1 and swap them
    /^   divide and exponentiate

```

Alas, `dc` does not allow for fractional exponents so this answer does not actually work for any given inputs above 1, and gives the wrong answer for 0 \< input \< 1. It does the same thing as many of the other programs though.
> 2 votes

# Answer
**Python 3: 34**

```
n=complex(input());print(n**(1/n))

```

Unless I'm missing something this would do nicely. I like that Python normally uses spaces, but this solution doesn't need them.
> 2 votes

# Answer
# 05AB1E, 3 bytes

```
Dzm

```

Explanation:

```
D    # Duplicate the input
 z   # Inverse, 1 ÷ input
  m  # Power, calculating input ** (1 ÷ input)

```

Try it online!.
> 2 votes

# Answer
# TI-Basic, 4 bytes

```
Ans^Ansֿ ¹

```

Since TI-Basic is tokenized, this code is a mere four bytes.
> 1 votes

# Answer
## QBIC, 9 bytes

```
:?a^(1/a)

```

Gets a numeric input from the command line and does the math...
> 1 votes

# Answer
# Mouse-2002, 13 bytes

```
x:x.b/x.&ROOT

```

Other programs assume the number's on the top of the stack and so shall I.

```
x:    ~ put TOS in x
x.    ~ push x
b /   ~ divide by 1
x.    ~ push x again
&ROOT ~ y to the x root

```
> 1 votes

# Answer
# Scala, 33 bytes

```
def f=(x:Double)=>Math.pow(x,1/x)

```
> 1 votes

# Answer
## Perl, 11 bytes

Added 2 bytes for `-pn`.

```
$_**=1/$_

```

Try it here !
> 1 votes

# Answer
# Pyth, 1 byte

```
@

```

Pyth takes implicit input, so `@` is really equivalent to `@QQ`, where `Q` is the evaluated input.

Try it online!
> 1 votes

# Answer
# Mumps, 14 Bytes

```
R I W I**(1/I)

```

R reads from input into variable I, and the W (write) statement does the mathematical calculations.

I will warn you: the output will be ugly as there are no implied newlines in Mumps, and at least the way I read the challenge, the OP didn't require them. If you did want cleaner output, add 2 bytes and add a newline:

```
R I W !,I**(1/I)

```
> 1 votes

# Answer
## SQL (MySQL), 60 bytes

```
CREATE FUNCTION G(X REAL) RETURNS REAL RETURN POWER(X,1./X);

```

Caps lock is cruise control for ~~cool~~ golf.
> 1 votes

# Answer
# Desmos, 14 bytes

```
a=1
\sqrt[a]{a}

```

Demonstration
> 1 votes

# Answer
# tcl, 23

I post two approaches which occupy the exact same number of bytes.

```
puts [expr $n**(1./$n)]

```

```
puts [expr $n**$n**-1.]

```

Available to test on http://rextester.com/EMW19680
> 1 votes

# Answer
# SmileBASIC, 18 bytes

```
INPUT X?POW(X,1/X)

```
> 1 votes

# Answer
# Common Lisp, 24 bytes

```
(lambda(x)(expt x(/ x)))

```

Try it online!
> 1 votes

# Answer
# Excel, 10 bytes

```
=A1^(1/A1)

```

Self explanatory.
> 1 votes

# Answer
# Vyxal, 2 bytes

```
Ėe

```

Try it Online!

The `e`s are coming!

```
 e # x to the power of
Ė  # 1/x

```
> 1 votes

# Answer
# Julia 1.0, 9 bytes

```
~x=x^x^-1

```

Try it online!

This solution handles both complex numbers and infinities.
> 1 votes

# Answer
# 05AB1E, 2 bytes

```
zm

```

Try it online!

```
zm  # full program
    # implicit input...
 m  # to the power of...
z   # 1 divided by...
    # implicit input
    # implicit output

```
> 0 votes

# Answer
# Thunno 2, 2 bytes

```
Ị*

```

Attempt This Online!

calculates the reciprocal, and `*` does exponentiation.
> 0 votes

---
Tags: code-golf, math, arithmetic
---