# Question
Title: Compute maximum excluding the current position
Given an array of integers A, the task is to output another array B of the same length so that B\[i\] is the maximum over A for every index that is not i. That is \\$B\[i\] = \max\_{i' \ne i} A\[i'\]\\$.

Examples:

```
A = [1, 5, -3, 4, 2]. B = [5, 4, 5, 5, 5]
A = [1, 2, 3]. B = [3, 3, 2]
A = [-1, -2, -3, -1]. B = [-1, -1, -1, -1]

```

The restriction is that your code **must run in linear time** in the length of the input array A.

The input will always contain at least two integers.

# Answer
# JavaScript (ES6), 54 bytes

*-2 thanks to @l4m2*

```
a=>a.map(v=>v-a?a:m,a.map(v=>a>v?m>v?0:m=v:(m=a,a=v)))

```

Try it online!

### Method

During the first pass, we compute \\$m\_0=\max A\_i\\$ and \\$m\_1=\max\_{i\neq j}A\_i\\$ where \\$j\\$ is the index of the first occurrence of \\$m\_0\\$. So we have \\$m\_1=m\_0\\$ if \\$m\_0\\$ appears more than once and \\$m\_1\<m\_0\\$ otherwise.

During the second pass, we replace each value \\$v\\$ in the input array with \\$m\_1\\$ if \\$v=m\_0\\$ or \\$m\_0\\$ otherwise.

In the JS implementation, we use `a` for \\$m\_0\\$ and `m` for \\$m\_1\\$.

### Commented

```
a =>           // a[] = input array,
               //       re-used as m0 (initially NaN'ish)
a.map(v =>     // (2nd pass) for each value v in a[]:
  v - a ?      //   if v is not equal to a:
    a          //     output a
  :            //   else:
    m,         //     output m
  a.map(v =>   //   (1st pass) for each value v in a[]:
    a > v ?    //     if a is a number greater than v:
      m > v ?  //       if m is a number greater than v:
        0      //         do nothing
      :        //       else:
        m = v  //         save v in m
    :          //     else:
      (        //
        m = a, //       save the previous maximum a in m
        a = v  //       save the new maximum v in a
      )        //
  )            //   end of map()
)              // end of map()

```
> 5 votes

# Answer
# Haskell \+ hgl, 34 bytes

```
zW ma<tl<g rS*^g lS

```

```
g h=h ma~<mn

```

Attempt This Online!

## Explanation

First this calculates the minimum value of the list (linear time). Then this scans the list rightwards calculating cumulative maxima, then it scans leftwards calculating cumulative maxima (both linear time). Finally it zips the two results together (lienar time). Since the cumulative maxima are the maxima of the prefixes / suffixes this means that when we zip them together we get the maximum of the values in the prefix before our value and the suffix after. This, naturally is the entire list other than the value in question. Since this is just a series of linear time operations the entire algorithm is linear time.

## Reflection

It feels wrong that `g` isn't shorter in point-free, however I think this is mostly because in normal golf, writing things in point free saves 2 bytes automatically by removing the function declaration. However here we *need* the function declaration (inlining `g` completely is very long) so point-free has to compete on even ground.

* `fid` should not be 3 bytes. This would make the point-free version of `g` shorter by a byte, replacing a `($ ma)` with `fi ma`, but would still be longer than the point-ful version.
* What this really wants is a way to zip with an offset. I'm not sure how universally applicable this idea is, but if implemented it would really simplify this answer.
> 4 votes

# Answer
# , 21 bytes

```
(={],1>./@}.i.|.[)>./

```

Try it online!

*Thanks to Jonathan Allen for pointing out I had missed the linear time constraint. This answer fixes that.*

*Inspired by Arnauld's answer*

* `>./` Max of all elements
* `1>./@}.i.|.[` Max of all elements after the first instance of the ordinary max is removed. Note because J does not have a "delete at" verb this is accomplished in a roundabout way: We rotate the elements left to put the normal max up front, then delete the first element, then take max.
* `],` Returns "ordinary max" catted with the "modified max" as just described.
* `=` Boolean mask indicating all positions equal to the ordinary max.
* `{` When the mask is `1`, return the modified max. Otherwise return the ordinary max.

## , orig quadratic time, non-competing, 7 bytes

```
1>./\.]

```

Try it online!

J's outfix solves this directly.
> 4 votes

# Answer
# Jelly, 13 bytes

```
œṡFṀṭʋṀiⱮCị⁸ʋ

```

A monadic Link that accepts the list and yields the maximised version.

**Try it online!**

### How?

```
œṡFṀṭʋṀiⱮCị⁸ʋ - Link: list of integers, A
      Ṁ       - maximum of {A} -> Max
     ʋ        - last four links as a dyad - f(A, Max):
œṡ            -   {A} split at first {Max}
  F           -   flatten {that}
   Ṁ          -   maximum of {that} -> SecondMax (possibly equal to Max)
    ṭ         -   tack {SecondMax} to {Max} -> TwoMaxes = [Max, SecondMax]
            ʋ - last four links as a dyad - f(TwoMaxes, A):
        Ɱ     -   map across {V in A} with:
       i      -     first 1-indexed index of {V} in {TwoMaxes} or 0 if not found
                     -> 1 if V==Max;
                        2 if V==SecondMax and SecondMax!=Max;
                        0 otherwise
         C    -   complement {those} (1-x) takes 0:1, 1:0, 2:-1
           ⁸  -   chain's left argument -> TwoMaxes
          ị   -   {complemented locations in TwoMaxes} index into {TwoMaxes}
                   (1-indexed and modular, so 1:Max, 0:SecondMax, -1:Max)

```

---

### Non restricted solution, 3 bytes

```
Ṁ-Ƥ - map max over overlapping outfixes of length one less than the input

```

Try it online!
> 4 votes

# Answer
# Python 3, 71 bytes

```
def f(a):h=nlargest(2,a);return[h[x>h[1]]for x in a]
from heapq import*

```

Try it online!

-4 bytes thanks to movatica

Compute the first and second maximum `h[0]` and `h[1]` of array `a`, then output `h[0]` or `h[1]` where appropriate.

Using `sorted` would take 20 fewer bytes than using `heapq.nlargest`, but would break the O(n) requirement.
> 3 votes

# Answer
# C (GCC) `-lm`, ~~97~~ ~~93~~ ~~90~~ ~~104~~ 101 bytes

-2 bytes thanks to @Arnauld
-1 byte thanks to @att
+14 bytes due to a bug fix (`m` was initialized with `a[0]` this causes problems when `a[0]` is the max)
-3 bytes thanks to @ceilingcat

```
f(n,a,m,M,i)int*a;{for(m=fmin(M=*a,a[1]),i=2*n;--i;)i>n?M<*++a?m=M,M=*a:m<*a?m=*a:0:(*a--=*a-M?M:m);}

```

Attempt This Online!

---

# C (GCC), ~~97~~ ~~93~~ ~~90~~ 104 bytes

```

f(n,a,m,M,i)int*a;{for(M=*a,m=M<a[1]?M:a[1],i=2*n;--i;)i>n?M<*++a?m=M,M=*a:m<*a?m=*a:0:(*a--=*a-M?M:m);}

```

Attempt This Online!
> 3 votes

# Answer
# JavaScript (Node.js), 71 bytes

```
x=>x.map(v=>v-n?m:M(...x.filter(u=>u-n||0*++n)),m=n=M(...x))
M=Math.max

```

Try it online!

-1 byte from Arnauld

After first meet of n, n is increased so it's larger than max, aka no more value can equal to n
> 2 votes

# Answer
# Python \+ NumPy, 44 bytes

```
lambda L:L[L.argpartition(-2)[(L<max(L))-2]]

```

Attempt This Online!

Takes and returns NumPy arrays. `numpy.argpartition` uses the linear time introselect algorithm to find in this case the second largest element (or rather its index) and split at this value.
> 2 votes

# Answer
# Google Sheets, 49 bytes

```
=let(a,A1:E1,m,max(a),sort(if(a=m,large(a,2),m)))

```

Put the input in cells `A1:E1` and the formula in cell `G1`.

`max()` and `large()` get evaluated once only. `sort()` is used as an array enabler and won't actually sort anything.
> 2 votes

# Answer
# , ~~20~~ 19 bytes

```
(]{~[=0{])(2$,\:,)/

```

Attempt This Online!

Copy of my answer in chat to the CMC version of this challenge.

-1 byte thanks to Jonah by spotting `\:~@,``,\:,`.

```
(]{~[=0{])(2$\:~@,)/  input: v = a vector
          (       )/  tops = reduce from right:
             \:~@,      concatenate and sort descending
                        (this sorts a constant(2 or 3) number of values,
                        so it runs in constant time per element)
           2$           take the first two (largest and 2nd largest)
(        )            run the rest with v on the left and tops on the right:
      0{]               the largest
    [=                  per element, 1 if it is equal to the largest,
                        0 otherwise
 ]{~                    per element, 2nd largest if ^ is 1, largest otherwise
                        (gives 2nd largest for largest and largest otherwise)

```

# Jelly, 9 bytes

```
=Ṁị;Ṣṫ-ʋ/

```

Try it online!

Jelly port of the above algorithm.

# , 16 bytes

```
(2$,\:,)/{~>./=]

```

Attempt This Online!

J backport of the Jelly port of the above algorithm, which turns out to be shorter! Does not reuse the "tops" array and computes the maximum again instead, which does not affect the overall time complexity.

# , 20 bytes

```
(>.|.)&(#$__,>./\)|.

```

Attempt This Online!

Port of Wheat Wizard's Haskell+hgl answer.

`f/\` normally creates prefixes and reduces each prefix by `f` from the right, which costs quadratic time, but it is special-cased for atomic and associative functions, which includes `>.` (max of two numbers).

```
(>.|.)&(#$__,>./\)|.  input: v = a vector
                  |.  reverse(v)
                      call the rest with v on the left and reverse(v) on the right:
(    )&(         )      apply the right to both sides:
             >./\         cumulative max (linear)
        #$__,             prepend __ (negative infinity) and
                          chop one from the end (linear)
 >.|.                   reverse the right side again and
                        take elementwise max (linear)

```
> 2 votes

# Answer
# Scala 3, ~~109~~ ~~94~~ 92 bytes

Saved 17 bytes thanks to @movatica

---

Golfed version. Attempt This Online!

```
a=>{val m=a.max;val s=if(a.count(_==m)>1)m else a.filter(_<m).max;a.map(x=>if(x<m)m else s)}

```

Ungolfed version. Attempt This Online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val tests = Array(
      (Array(1, 5, -3, 4, 2), Array(5, 4, 5, 5, 5)),
      (Array(1, 2, 3), Array(3, 3, 2)),
      (Array(-1, -2, -3, -1), Array(-1, -1, -1, -1))
    );

    tests.foreach { case (a, b) =>
      val c = f(a)
      println(s"${a.mkString("[", ", ", "]")} --> Expected: ${b.mkString("[", ", ", "]")}, Actual: ${c.mkString("[", ", ", "]")}, Result: ${b.sameElements(c)}")
    }

  }

  def f(a: Array[Int]): Array[Int] = {
    if (a.length <= 1) return a

    val maxVal = a.max
    val secondMaxVal = if (a.count(_ == maxVal) > 1) maxVal else a.filter(_ != maxVal).max

    a.map(x => if (x == maxVal) secondMaxVal else maxVal)
  }
}

```
> 2 votes

# Answer
# APL(NARS), 119 chars

```
r←f w;a;b;n;i;t
n←≢w⋄i←2⋄a←b←w[1]
→4×⍳i>n⋄→3×⍳∼b<t←w[i]⋄a←b⋄b←t
i+←1⋄→2
i←1⋄r←⍬
t←w[i]⋄→6×⍳∼t=b⋄r,←a⋄→7
r,←b
→5×⍳n≥i+←1

```

15+17+29+7+7+23+4+10 +7=119

2 pass of the array, one for to find the maxs, and one for build the result array. Test&how to use. one not difficult solution but possible the more long and lazy.

```
      f 1 2 3
3 3 2
      f 1 1
1 1
      f ,1
1

```
> 1 votes

# Answer
# Charcoal, 26 bytes

```
≔⌈θη≔⌕θηζ≔⌈Φθ⁻κζζＩＥθ⎇⁼ιηζη

```

Try it online! Link is to verbose version of code. Explanation:

```
≔⌈θη

```

Get the maximum value of the input list.

```
≔⌕θηζ

```

Get the index of its first occurrence.

```
≔⌈Φθ⁻κζζ

```

Make a new list excluding that index, and take the maximum of that.

```
ＩＥθ⎇⁼ιηζη

```

Output that value for the maximum values in the list, and the maximum for the other values.

By comparison a fully golfed version would be ~~19~~ 9 bytes:

```
ＩＥθ⌈Φθ⁻μκ

```

Try it online! Link is to verbose version of code. Runs in O(n²) time. Explanation: For each element, creates a new list without that element, and takes the maximum of that list.
> 1 votes

# Answer
# Perl 5 `-MList::Util=max,first -a`, 81 bytes

```
$m=max@F;$i=first{$F[$_]==$m}@t=0..$#F;$;=max@F[grep$i-$_,@t];say$_-$i?$m:$;for@t

```

Try it online!
> 1 votes

# Answer
# Python 3.8 (pre-release), ~~72~~ 66 bytes

```
def f(A):B=len(A)*[A.pop(i:=A.index(max(A)))];B[i]=max(A);return B

```

Try it online!

First, observe that `B` contains the second largest value of `A` at position `i` iff the largest value in `A` exists exactly once, at that very position. In all other cases (largest value exists more than once or `A` holds only one value), `B` consists solely of `max(A)`. So all we have to handle is that one special case.

Ungolfed:

```
def f(A):
  l = len(A)
  m = max(A)
  B = l * [m]
  i = A.index(m)
  A.pop(i)
  B[i] = max(A)
  return B

```

As `max` and `index` are linear operations and `len`, `pop` and assignment are constant time, the runtime is `O(3n) = O(n)`
> 1 votes

# Answer
# APL+WIN, 22 bytes

Prompts for vector. Index origin = 0

```
⌈/0 1↓(⍳⍴n)⌽(2⍴⍴n)⍴n←⎕

```

Try it online! Thanks to Dyalog Classic
> 1 votes

---
Tags: code-golf, restricted-complexity
---


title: Mousetail's Sequence

text:
# Question
Title: Mousetail's Sequence
I define mousetail's sequence as follows:

* If the nth element of the sequence is q, then n+1 must appear q times in the sequence
* The sequence is weakly monotonically increasing (i.e. no lower number may follow a higher number)
* f(1)=1

I'll show an example of how this works:

* the first element is 1
* after the 1, come 1 2s
* then 2 3s, since f(2)=2
* then three 4s and three 5s, since f(3)=f(4)=3
* then four 6s, four 7s, four 8s, five 9s, five 10s, and five 11s
* six 12s, six 13s six 14s, six 15s, seven 16s etc.

Thus, it comes out to be

```
1,2,3,3,4,4,4,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,9,10,10,10,10,10,11,11,11,11,11,12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,14,14,...

```

Sequence rules apply, you may either:

* Given n, output the nth element of the sequence
* Given n, output the first n terms
* Output the sequence infinitely

Either 0 or 1 based indexing is acceptable.

# Answer
# JavaScript (ES6), 29 bytes

This is based on the recurrence formula given for A001462, which is a very similar sequence found by bsoelch.

Returns the \\$n\\$-th term, 1-indexed.

```
f=n=>n<3?n:1+f(n-f(f(n-1)-1))

```

Try it online!

### Formula

$$\begin{cases}a(1)=1\\ a(2)=2\\ a(n)=1+a(n-a(a(n-1)-1)),\\:n\ge 3\end{cases}$$

---

# JavaScript (ES6), 36 bytes

This is my original answer. Longer but faster.

Returns the \\$n\\$-th term, 0-indexed.

```
f=(n,i=0,k)=>i<n?f(n,i+f(k),-~k):-~k

```

Try it online!

### Method

We don't need to store the sequence explicitly. We just have to keep track of the current position \\$i\\$ and current value \\$k\\$, and use recursion to get the previous values.

### Commented

```
f = (         // f is a recursive function taking:
  n,          //   n = input
  i = 0,      //   i = current index
  k           //   k = current value, minus 1
) =>          //
i < n ?       // if i is less than n:
  f(          //   do a recursive call:
    n,        //     pass n unchanged
    i + f(k), //     add f(k) to i
    -~k       //     increment k
  )           //   end of recursive call
:             // else:
  -~k         //   return k + 1

```
> 10 votes

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

```
{(x#&0 1,)/x}

```

Try it online!

A function returning the first `x` values of the sequence.

`(...)/x` Iterate until convergence, starting with `x` (could be any non-negative integer):
`0 1,` Prepend 0 and 1 to the current list.
`&` Where. For boolean vectors this gives the indices of 1s, for positive integers each index is repeated by the value.
`x#` Take the first `x` values from the resulting list.
> 7 votes

# Answer
# Python, ~~40~~ 38 bytes

-1 thanks to @Mukundan314, additional -1 thanks to @JonathanAllan

```
f=lambda x:x*(x<3)or-~f(x-f(f(x-1)-1))

```

A port of @Arnauld's Javascript solution.

Attempt This Online!

# Python, 62 bytes

```
def f():
 yield 1
 for i,x in enumerate(f()):yield from[i+2]*x

```

Attempt This Online!
> 6 votes

# Answer
# Python, 42 bytes

```
a=[i:=1]
for x in a:print(x);a+=[i:=i+1]*x

```

Attempt This Online!
> 4 votes

# Answer
# Jelly, 9 bytes

```
1Jx$Ż‘Ɗ¡ḣ

```

A monadic Link that accepts an integer, \\$n\\$, and yields a list of the first \\$n\\$ terms.

**Try it online!** Very inefficient! Remove  to see the terms found before heading to \\$n\\$.

### How?

```
1Jx$Ż‘Ɗ¡ḣ - Link: non-negative integer, Terms (n)
1         - set the left argument, Current, to one
       ¡  - repeat {Terms} times:
      Ɗ   -   last three links as a monad - f(Current):
   $      -     last two links as a monad - f(Current):
 J        -       range of length
  x       -       times {Current} (repeat indices by Current values respectively)
    Ż     -     prefix a zero
     ‘    -     increment
        ḣ - head to index {Terms}

```
> 3 votes

# Answer
# Haskell, ~~39~~ 30 bytes

*Thanks to ovs*

```
w=1:do n<-[0..];n+2<$[1..w!!n]

```

Try it online!

Constructs the list as a fixed point.
> 2 votes

# Answer
# Uiua 0.8.0, 22 bytes SBCS

```
⊡:⍥(⊂:↯⊃⊡(+1)⊢⇌..),0_1

```

Try on Uiua Pad! Takes an integer \\$n\\$ and returns the \\$n\\$th term.

## Explanation

```
0_1 # array [0,1]
,   # duplicate input to top of stack
⍥(  # repeat n times
  .. # dup list twice
  ⊢⇌ # last element
  ⊃⊡(+1) # fork: get both the element at that index of the list and last element + 1
  ↯ # reshape: repeat last + 1 that many times
  ⊂: # join the array to the end
)
⊡: # pick the nth element

```
> 2 votes

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

```
2Ýλè<₅₆>

```

Outputs the 1-based \\$n^{th}\\$ value.

Try it online or verify the infinite sequence.

**Explanation:**

Uses the following recursive 0-based sequence to output the 1-based \\$n^{th}\\$ term:

$$a(0)=0, a(1)=1, a(2)=2\\ a(n)=a(n-a(a(n-1)-1))+1$$

```
  λ       # Start a recursive environment
   è      # to output the 0-based (implicit) input'th term
          # (which is output implicitly at the end)
2Ý        # Starting with a(0)=0, a(1)=1, and a(2)=2
          # And where every following a(n) is calculated as:
          #  (implicitly push a(n-1)):                  a(n-1)
    <     #  Decrease it by 1:                          a(n-1)-1
     ₅    #  Pop and take that term:                  a(a(n-1)-1)
      ₆   #  Pop and take the (n-value)'th term:  a(n-a(a(n-1)-1))
       >  #  And increase that by 1:              a(n-a(a(n-1)-1))+1

```
> 2 votes

# Answer
# Vyxal 3, 14 bytes

```
1Ọw{mvᵇiᵂ…YᵛỌJ

```

Try it Online!

```
1Ọw{mvᵇiᵂ…YᵛỌJ
1Ọw             # Output 1 without popping, wrap in list
   {            # While true
    mv          #  Decrement the current iteration n
      ᵇi        #  Index into list without popping
        ᵂ…      #  Stash indexed item, add 2 to n-1 -> n+1, unstash item
          Y     #  Repeat n+1 item at index n-1 times
           ᵛỌ   #  Print each element without popping
             J  #  Join repeated list with original list

```

Created with the help of Luminespire.
> 1 votes

# Answer
# Google Sheets, 62 bytes

```
=let(f,lambda(f,n,if(n<3,n,1+f(f,n-f(f,f(f,n-1)-1)))),f(f,A1))

```

Put \\$n\\$ in cell `A1` and the formula in cell `B1`. The output is the \\$n\\$th term.

Using the recursive function in Arnauld's JavaScript answer. Google Sheets supports recursion to a depth of 10,000 but the calculation limit is met much earlier here because the function branches several times. The formula will start erroring out at \\$n\\$ = 34.

This iterative implementation will handle much bigger values of \\$n\\$ (**75 bytes**):

```
=reduce(,sequence(A1),lambda(a,n,iferror({a;sequence(index(a,n),1,n,)},1)))

```

Put \\$n\\$ in cell `A1` and the formula in cell `B1`. Output appears in cells `B2:B` and contains elements up to and including the element whose value is \\$n\\$. To make the number of elements in the output *limited* to \\$n\\$ instead (**99 bytes**):

```
=array_constrain(reduce(...),A1+1,1)

```
> 1 votes

# Answer
# Charcoal, ~~20~~ 19 bytes

```
ＦＮ⊞υ∨¬υ⊕§υ±§υ⁻⌈υ²Ｉυ

```

Try it online! Link is to verbose version of code. Outputs the first `n` values. Explanation: Adapted my efficient answer to use @Arnauld's recurrence relation.

```
ＦＮ

```

Repeat `n` times.

```
⊞υ∨¬υ⊕§υ±§υ⁻⌈υ²

```

Push `1` as the first value, otherwise use the recurrence relation. Charcoal's cyclic indexing allows this to work for `n=2` as a degenerate case since there is only one value in the array at this point.

```
Ｉυ

```

Output the `n` results.
> 1 votes

# Answer
# Scala 3, 96 bytes

A port of @Command Master's Python code in Scala.

---

Golfed version. Attmept This Online!

```
def f():Iterator[Int]=Iterator(1)++f().zipWithIndex.flatMap{case(x,i)=>Iterator.fill(x)(i+2)}

```

Ungolfed version. Attempt This Online!

```
object Main {
  def main(args: Array[String]): Unit = {
    f().take(100).foreach(x => print(s"$x "))
  }

  def f(): Iterator[Int] = Iterator(1) ++ f().zipWithIndex.flatMap { case (x, i) =>
    Iterator.fill(x)(i + 2)
  }
}

// 1
// 1 2                  // append 1 number.two
// 1 2 3 3              // append 2 number.three
// 1 2 3 3 4 4 4 5 5 5  // append 3 number.four  append 3 number.five
//...

```
> 1 votes

# Answer
# Uiua SBCS, 12 bytes

```
↙:⍥(⊚⊂⇡2),[]

```

Try it!

Very inefficient. An adaptation of ovs' K answer. Returns the first n elements of the sequence.

```
↙:⍥(⊚⊂⇡2),[]
          []  # push empty list
         ,    # copy input to top of stack
  ⍥(    )     # repeat [input] times
      ⇡2      # push [0 1]
     ⊂        # prepend
    ⊚         # repeat each index [value] times
↙:            # take the first [input] values

```
> 1 votes

# Answer
# , 33 bytes

```
`?`=\(n)`if`(n<3,n,1+?n-?-1+?n-1)

```

Attempt This Online!

Port of @Arnauld's JavaScript answer.

# , 43 bytes

```
\(n)rep(seq(x<-c(1,1,rep(1:n,1:n-1))),x)[n]

```

Attempt This Online!

Straightforward generation of the sequence.
> 1 votes

# Answer
# Ruby, 67 bytes

67 bytes, it can be golfed much more.

---

Golfed version. Try it online!

```
f=Enumerator.new{|y|y<<1;e=f.dup;i=2;loop{e.next.times{y<<i};i+=1}}

```

Ungolfed version. Try it online!

```
def f
  Enumerator.new do |yielder|
    yielder << 1
    enum = f
    i = 2
    loop do
      x = enum.next
      x.times { yielder << i }
      i += 1
    end
  end
end

f.lazy.take(100).each { |x| print "#{x} " }

```
> 1 votes

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

```
<3?U:ÒßU´-ßÓß

```

Try it

-1 byte thanks to Shaggy

This uses the same method as Arnauld’s JavaScript solution, but it is rearranged slightly.

A direct port is 16 bytes:

```
<3?U:ßU-ßßUÉ É)Ä

```

Try it

This isn’t efficiently packed, though; there’s a space and a close parenthesis, which are generally good to try to avoid in Japt.

This is the obvious method, using the commonly used postfix decrement `É` (`-1`) and increment `Ä` (`+1`). Japt actually does have prefix equivalents for both of these, however: `Ò` (`-~`) for increment, and `Ó` (`~-`) for decrement. In this case, both of the parentheses can be omitted by using prefix operators.

The 16-byte version is the same as Arnauld’s:

```
f=n=>n<3?n:f(n-f(f(n-1)-1))+1

```

This version is closer to:

```
f=n=>n<3?n:-~f(n-f(~-f(n-1)))

```

where the trailing parentheses can be omitted in Japt.

Shaggy's suggestion changes that final `-1` to an in-place decrement:

```
f=n=>n<3?n:-~f((n--)-f(~-f(n)))

```

The difference is that now, that argument to the final recursion can also be omitted, saving a byte.
> 1 votes

# Answer
# TypeScript's type system, 113 bytes

```
//@ts-ignore
type G<N,I=[],O=[[1]],Z=[...I,1],S=O[I["length"]]>=I extends N?S:G<N,Z,[...O,...{[_ in keyof S]:Z}]>

```

Try it at the TypeScript playground! I/O is with unary numbers represented as tuples of 1s.

Or, **~~125~~ 122 bytes** with I/O as decimal numbers:

```
//@ts-ignore
type G<N,I=[],O=[[1]],L="length",Z=[...I,1],S=O[I[L]]>=I[L]extends N?S[L]:G<N,Z,[...O,...{[_ in keyof S]:Z}]>

```

Try it at the TypeScript playground

This keeps track of the sequence O, the requested entry N, and the current iteration number I. It continuously appends I + 1 repeated `O[I]` times to O, until I is equal to N, at which point `O[N]` (the Nth entry) is returned.

## TypeScript's type system, 113 bytes

```
//@ts-ignore
type F<A,B="">=B extends`${A}${infer Z}`?Z:A extends"1"|"11"|"111"?A:`1${F<F<F<F<1,F<F<1,A>>>>,A>>}`

```

I/O is unary numbers represented as string types of the character 1.

This is a port of Arnauld's JavaScript solution. It ends up pretty long in TypeScript because we don't have numeric comparison or subtraction built-in.
> 1 votes

# Answer
# JavaScript (Node.js), 58 bytes

```
for(o=[0,j=i=1];;console.log(j=o[++i]))for(;j--;)o.push(i)

```

Attempt This Online!

I tried another approach, this one generates the sequence infinitely.
> 1 votes

# Answer
# Clean, 55 bytes

```
import StdEnv
w=[1: $0]
$s=[s+2\\_<-[1..w!!s]]++ $(s+1)

```

Try it online!

My first clean answer. Probably could be improved.

# Clean, 59 bytes

```
import StdEnv
g[h:t]=[1\\_<-[1..h]]++[x+1\\x<-g t]
w=g[1:w]

```

Try it online!

This is an alternate approach. This feels very close to beating the other one, but I can't quite get it to work out.
> 1 votes

# Answer
# Pip, 18 bytes

```
Fi,aoAL:i+2RL Po@i

```

Given an input `a`, outputs the first `a` terms. Attempt This Online!

### Explanation

```
Fi,aoAL:i+2RL Po@i
                    ; a is command-line argument; o is 1 (implicit)
Fi,a                ; For i in range(a):
              Po@i  ; Print element of o at index i
        i+2RL       ; Make a list of that many copies of i+2
                    ; (It has to be i+2, not i+1, because Pip uses 0-indexing)
    oAL:            ; Append that list to o

```

Created with the help of Luminespire.

(Note that `o` is a scalar on the first iteration, but as soon as `AL` is used to append something to it, it gets converted to a list.)
> 1 votes

# Answer
# Haskell \+ hgl, 17 bytes

```
w=jn$zW rl(1:w)nN

```

Attempt This Online!

## Explanation

Like the my other Haskell answer this calculates the sequence as the fixed point of a function, however it implements that function pretty differently.

If the list is `w` then we zip `1:w` with the natural numbers using `rl`, a function which repeats the input n times. Then we concat together the result.

## Alternate solutions

```
w=jn$ixo 1frl$1:w

```

Attempt This Online!

```
yy$jn<ixo 1frl<K1

```

Attempt This Online!

## Reflection

* A couple days ago I mentioned wanting a function which zips and then concats. That would obviously be very useful here, but I still haven't implemented it.
* There should be an infix version of `zW`.
* `ixo` should have a version precomposed with small values. Maybe an infix function as well.
> 0 votes

---
Tags: code-golf, sequence
---


title: iHateOddNumbers

text:
# Question
Title: iHateOddNumbers
# Task

Given a non-negative number, check if it's odd or even. In case it's even, output that number. Otherwise, throw any exception/error that your language supports, and stop the program.

# Example with Python

Input: `1`
Output:

```
Traceback (most recent call last):
  File ".code.tio", line 1, in <module>
    IfYouWantThenThrowThis
NameError: name 'IfYouWantThenThrowThis' is not defined

```

# Another example

Input: `2`
Output: `2`

# Rules

* This is , so the answer with shortest bytes wins.
* These loopholes are, obviously, forbidden.
* Standard code-golf rules apply.
* Please specify the language you are using and the amount of bytes.
* It would be great if you would put a link to a sandbox where your code can be ran in action, such as TIO.
* Explaining your code is very welcomed.

---

# LEADERBOARD

```
<script>var QUESTION_ID=229052,OVERRIDE_USER=0;</script><style>body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&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(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.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(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}</script><link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <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><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```

# Answer
> 26 votes
# Jelly, 3 bytes

```
MḂ¡

```

Try it online! (even) and Try it online! (odd)

## How it works

`M` is an atom meaning "Given a list, yield the indices of that maximal elements". Now, typically, when given integer arguments to its array functions, Jelly promotes them to either a range, to digits, or just wraps it. Unfortunately, (I'm guessing due to `M`'s age - it was one of the earliest builtins in Jelly), `M` doesn't do this, and throws an error as it can't iterate over an integer.

How the code actually works:

```
MḂ¡ - Main link. Takes N on the left
 Ḃ  - Bit; Calculate N % 2
  ¡ - Do the following a number of times equal to N % 2:
M   -   Run the M builtin on N

```

If the input `N` is even, then  yields `0` and `¡` runs `M` on `N` `0` times i.e. an identity function.

If the input is odd, then  yields `1` and `¡` runs `M` once, which is enough to error it

# Answer
> 37 votes
# Python 2, 16 bytes

```
lambda n:n<<n%-2

```

Try it online!

The expression `n%-2` equals 0 for even `n` and -1 for odd `n`. Bit-shifting `n` by 0 positions leaves it unchanged, but for -1 positions it gives an error for "negative shift count".

# Answer
> 26 votes
# Hexagony, 13 bytes

```
?#\.@!:.!_@\|

```

Try it online!

Expanded: (Made using Hexagony Colorer)

This code is built around Hexagony's `#` operator. Hexagony initializes with 6 IP's, 1 in each corner of the code box, with the 0th one, the one in the top left, being active in the beginning. The `#` operator takes the value of the current memory cell mod 6, and then sets the corresponding IP as the active one. So making an even/odd checker is a matter of using the `#` operator and then having IP's 1,3, and 5 perform the 'odd' action, and IP's 0,2, and 4 perform the 'even' action. The consequence of doing it this way is that there are 6 separate paths that each need to be mapped to the correct endpoint, hence the mess of paths. In this case, the odd action is `:` (attempt to divide two non-existent values, resulting in a divide by zero error) and the even action is `!@` (print and terminate). To make it hopefully a bit more readable, here's a very low-tech drawing of the paths:

The paths are:

* n%6 == 0 : Green
* n%6 == 1 : Yellow
* n%6 == 2 : Blue
* n%6 == 3 Pink
* n%6 == 4 : Orange
* n%6 == 5 : Red

I'm pretty confident 12 bytes is possible, and potentially even shorter. Not sure if there's a better approach entirely, but with this method, it seems just about brute-force-able. It seems it should only require `?`,`#`, no more than 3 each of `@`,`!`, and `:`, and some control flow characters.

# Answer
> 16 votes
# x86 Machine Code, 5 bytes

```
A8 01 74 01 F4

```

Takes the integer value of your choice in the `EAX` register, halts the CPU if the number is odd, or continues execution harmlessly if the number is even.

Ungolfed assembly language mnemonics:

```
A8 01         test   al, 1
74 01         jz     IsEven
F4            hlt
          IsEven:

```

The first two instructions (`test`+`jz`) are the fastest and smallest way to check whether an integer value is even or odd in x86 machine code. The reason they work is hopefully obvious: for binary numbers, the least-significant bit (bit 0) is only set if the number is odd (for even numbers, the least-significant bit is clear). Therefore, testing the least-significant bit and seeing if it is non-zero is the easiest, simplest, smallest, and fastest way to see whether a number is even.

Here, I've used `jz` to jump if the zero flag (ZF) is set—i.e., if the bit we tested (bit 0) was zero, which means that it jumps if the number was even. Note that it jumps *over* the halt (`hlt`) instruction if the input value was even. If the input value was odd, then execution falls through the jump, and ends up halting the CPU.

If you don't like `hlt` because you don't think that counts as throwing an exception/error, then replace it with an `int 3` instruction, which is also only 1 byte (`0xCC`), and thus doesn't change the overall code size (5 bytes). The `int 3` instruction is the trap to a debugger.

The only way you could really argue that this code is cheating is that it doesn't "output" that number. I'd say it does: it allows execution to continue past the point where that number was generated, which is a lot like outputting it. You don't get any output for odd inputs; you can only get output for even inputs. Besides that, I think this is allowed by many, many different agreed-upon input/output methods.

---

# x86 Machine Code, 6 bytes (non-competing)

A division by 0 is another obvious solution, but it doesn't save any bytes. Even if you are willing to allow clobbering the input value, in order to arrange for a division by zero, you have to negate somewhere (either the original value, or the isolated LSB), and that requires an extra instruction (either `XOR`ing with 1, or a `NOT`), which means 2 extra bytes.

```
A8 01         test   al, 1
34 01         xor    al, 1
F6 F0         div    al

```

That's 6 bytes, and I'm not even sure that I can figure out how to justify this clobbering of the original input value as being consistent with the requirements of the challenge to "output" the value.

To avoid clobbering, there are a few different options. For example, we can stipulate that the input is taken in a different register (say, `ECX`). But this means that we can't use the short "implied accumulator" encoding of `test` and `xor`, so it costs us at least two bytes. (We could use `not` with the full register before the `test` to invert the bits, which is encoded in only 2 bytes, but that defeats the point, which is to avoid clobbering the input.) Or, we could `push` and `pop` the input, but that also costs two extra bytes (one for each, `push` and `pop`). Maybe I'm missing something obvious, but I'm not seeing a better solution here.

# Answer
> 15 votes
# Java (JDK), 10 bytes

```
n->n/=~n&1

```

Try it online!

## Explanations

This code basically divides by zero when the input number is odd or by one when it is even.

### `~n`

The `~` character negates each bit of `n` because `n&1` returns `0` when `n` is even and `1` when it's odd, but we want the opposite: `0` when odd (to make it fail) and `1` when even to return it, so `~` is the easiest way to negate the last bit.

### `~n&1`

This is the part that reduces `n` to either `0` or `1`. `~n&1` is not exactly the same as `~n%2` because, in Java, `%2` keeps the signum of `n`, and since we definitely swap the signum with `~`, we'd always end up with negative number, not matter what `n` is: if `n<0` we'd get negative divided by positive, and if `n>=0`, we'd get positive divided by negative.

We want to divide by `0` or by `1`, nothing else. Only `&1` can guarantee that. No matter what, the operator priority will first evaluate `~n` so no parenthesis are required.

### `/=`

This bit is weird. Why do we do divide and assign, instead of just dividing? Technically, `n/~n&1` will be parsed as `x=n/~n` then `x&1`. This is not the behavior we want: `n/~n` is always equal to `0`. What we want is to have `n/(~n&1)`. It could work well, but the whole answer would be `n->n/(~n&1)`. The `/=` operator is a shortcut to that as it evaluates the right-hand side entirely, so we can get rid of parenthesis, gaining one byte. Assigning is a side effect we can live with.

# Answer
> 13 votes
# MATLAB/Octave, ~~17~~ ~~13~~ 12 bytes

*-4 bytes thanks to Sisyphus*

```
@(x)x(i^2^x)

```

Try it online!
Anonymous function. Throws indexing error for odd numbers.

This function returns element from input at index `i^2^x = (-1)^x`, so

* at index `1` for even numbers (which is input itself)
* at index `-1` for odd numbers (which is invalid index since indices in MATLAB start at 1)

# Answer
> 11 votes
# Wolfram Language (Mathematica), 10 bytes

I think this uses an approach that isn't yet represented in the other answers.

*–1 byte thanks to att!*

```
#+0^I^#^2&

```

Try it online! Here `I` represents the imaginary number *i*. Since the square of every even number is a multiple of 4, `I^#^2` equals 1 when the input is even, and so `0^I^#^2` becomes \\$0^1\\$ which is a perfectly nice 0 to add to the input. However, since the square of every odd number is one more than a multiple of 4, `I^#^2` equals *i* when the input is odd, and so `0^I^#^2` becomes \\$0^i\\$ which throws an "Indeterminate expression " error.

## first submission: 11 bytes

```
#+0^(-1)^#&

```

Try it online! Since –1 to an even power equals 1, `0^(-1)^#` becomes \\$0^1\\$ when the input is even, which is a perfectly nice 0 to add to the input; however, since –1 to an odd power equals –1, `0^(-1)^#` becomes \\$0^{-1}\\$ (the reciprocal of 0) when the input is odd, which throws an error.

# Answer
> 10 votes
# Vyxal, 2 bytes

```
₂ḭ

```

Try it Online!

-1 thanks to Aaron Miller

```
₂  # Is_even(n) (Vyxal has no booleans, only 0 and 1)
 ḭ # Integer division (ordinary division doesn't error on 0)

```

# Answer
> 9 votes
# , 20 bytes

```
n=scan();n+(n%%2&&a)

```

Try it online!

The `&&` operator is logical AND, evaluating left to right until the result is determined. If `n` is even then `n%%2` is `0`, coerced to `FALSE`, and the `a` part of the expression is therefore not evaluated. We then output `n+0`, ie `n`.

If `n` is odd, then `n%%2` is 1, coerced to `TRUE`, and we need to evaluate the `a` part of the expression to determine the result of `n%%2&&a`. Since `a` is undefined, this produces an error.

This strategy comes out 3 bytes shorter than Dominic's strategy with `if`.

# Answer
> 8 votes
# PowerShell, ~~31~~ ~~25~~ ~~14~~ 19 bytes

*-6 bytes thanks to @mazzy*

```
param($n)$n/!($n%2)

```

Try it online!

Calculates the modulo of the input number and `2`, implicitly converts the result to a boolean in order to negate it, then divides the input number by the negation. Inadvertently ditched the spec for a while there, sorry!

# Answer
> 7 votes
# Python 2, 17 bytes

```
lambda n:n/(~n%2)

```

Try it online!

thanks to @hyper-neutrino for -4 bytes

# Python 3, 24 bytes

```
lambda n:n%2and 1/0 or n

```

Try it online!

# Answer
> 7 votes
# Japt, ~~6~~ 5 bytes

Throws ~~a `TypeError`~~ an overflow error on odd numbers. ***Still** convinced* there must be a much shorter way `/v` would work if JavaScript errored on division by 0.

```
*v ªß

```

Try it

```
*v ªß     :Implicit input of integer
*         :Multiply by
 v        :  Divisible by 2?
   ª      :Logical OR with
    ß     :A recursive call

```

# Answer
> 7 votes
# Factor, 15 bytes

```
[ 2 / 1 shift ]

```

Try it online!

*Thanks to @umnikos*

# Factor, 19 bytes

```
[ dup 1 + 2 mod / ]

```

Try it online!

Throws a divide by zero error on odd numbers, while returning even numbers.

## Explanation:

* `dup` Duplicate the input.

**Stack:** (e.g.) `2 2`
* `1 +` Add one.

**Stack:** `2 3`
* `2 mod` Modulo two.

**Stack:** `2 1`
* `/` Divide. (Here is where the error happens for odd input.)

**Stack:** `2`

Here's a slightly longer version that simply asserts the number is not odd:

```
[ dup odd? f assert= ]

```

# Answer
> 7 votes
# JavaScript (Node.js), 10 bytes

```
n=>n%2?_:n

```

Try it online!

Not a very hard answer

# Answer
> 7 votes
# MMIX, 12 bytes (3 instrs)

```
ihateodds   PBEV  $0,0F     // if(n even) goto ret;
            LDVTS $0,$0,6   // privileged instruction
0H          POP   1,0       // ret: return n

```

The `LDVTS` tries to make whatever memory page the input points to RWX in the cache, though not in the page table (if the input is one more than a multiple of 8). This is a privileged instruction for obvious reasons.

# Answer
> 7 votes
# PHP, 14.

```
die($argv[0]);

```

There's no need to differentiate odd and even. The criteria say odd numbers can display *any* error, while even ones should be displayed.

Since the criteria allow for ANY error on an even number, and die() displays an error and terminates, the input is fine as an error.

The criteria allow for even numbers to be displayed in any manner, including as an error, so again, the input is fine as an error.

But if die() isn't accepted as an error, and a genuine terminating error's required... **~~27~~ 26 bytes**. Sadly we can't use `die()` here...

```
echo($a=$argv[1])%2?$b:$a;

```

If warnings are acceptable as errors, then in the comments Matthew Anderson's suggestion to use division by zero also gives us **26 bytes**:

```
echo($a=$argv[1])/!($a%2);

```

# Answer
> 7 votes
# Python 3, 17 bytes

```
lambda x:[x][x%2]

```

Try it online!

It's very simple - construct a list with a single (zeroth) number and take an element of it with index equal to that number modulo 2. Since there is no element 1, it will obviously throw an exception on odd input.

# Answer
> 6 votes
# , ~~25~~ ~~23~~ 22 bytes

*Edit: -2 bytes after looking at ophact's answer, and then -1 byte thanks to Robin Ryder*

```
`if`((n=scan())%%2,,n)

```

Try it online!

Throws an 'argument is missing' error when `n` is odd and the `if` expression tries to read the missing expression that should be between the two commas.

# Answer
> 6 votes
# Wolfram Language (Mathematica), 13 bytes

```
#/Mod[#+1,2]&

```

Try it online!

-1 byte from @att

# Answer
> 6 votes
# C (gcc), ~~28~~ ~~15~~ 14 bytes

-13 thanks to Jonathan Allan
-1 thanks to Olivier Grégoire

```
f(a){a/=~a&1;}

```

Try it online!

How `~a&1` works is explained in this solution.

# Answer
> 6 votes
# Retina 0.8.2, 13 bytes

```
+`[13579]$
99

```

Try it online! Explanation: If the number is odd, simply keeps appending `9`s until Retina eventually runs out of memory, or until TIO kills it, whichever is sooner.

If you want a more direct error, then for 21 bytes:

```
[13579]$
9999999999$*

```

Try it online! Explanation: Tries to append more than a 32-bit integer length of `9`s to the odd input, which throws an OverflowException.

# Answer
> 6 votes
# AWK, 11 10 bytes

```
1/($1%2-1)

```

Try it online!

*Thanks to tail spark rabbit ear for helping drop one char...*

Divides by zero if the number is odd, otherwise the test is truthy and the default action prints the commandline..

# Answer
> 6 votes
# APL (Dyalog Unicode), 7 bytes (SBCS)

Anonymous tacit prefix function

```
⊢÷1-2|⊢

```

Try it online!

the argument

`÷` divided by

`1-` one minus

`2|` the division remainder when 2 divides

the argument

Or in other words:$$x\over{1-\Big({x\over2}-\big\lfloor{x\over2}\big\rfloor}\Big)$$

# Answer
> 6 votes
# Perl 5 `-p`, 9 bytes

```
$_%2&&die

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 3 bytes

```
Èи¿

```

Try it online!

or

```
È×F

```

Try it online!

`È` checks if the input is even. Returns `1` for even numbers, `0` for odd numbers.

* `и` creates a list of this many copies of the input, and `¿` calculates the gcd of the list and throws an error for empty lists
* `×` repeats the input as a string this many times. This results in the input for even inputs and the empty string for odd inputs. `F` is a for loop which crashes if it gets the empty string as an argument. In the end the stack is empty and the input is implicitly printed. `F` could be any of `E`, `F`, `G` and `ƒ`.

# Answer
> 5 votes
# Zsh (math function), 14 bytes

```
((1/1&~$1,$1))

```

Try it online!

Unlike in Bash, C and many other languages, in Zsh `&` binds more tightly than `/` by default, allowing us to get division by zero on odd numbers with just `1 / 1 & ~$1`.

(Zsh does have a `C_PRECEDENCES` option which changes arithmetic binding to the traditional order.)

# Answer
> 4 votes
# Jelly, 4 bytes

```
ḂNXo

```

Try it online!

# Jelly, 5 bytes

```
%2NXo

```

Try it online!

Look ma, no unicode!

```
ḂNXo  Main Link
Ḃ     Same thing as %2. 1 if it's odd, 0 if it's even.
 N    Negate. -1 if it's odd, 0 if it's even.
  X   Random number. Errors with -1 as input, returns 0 with 0 as input.
   o  Logical OR. If the input was odd, the program's already errored. Otherwise, it's 0,
      so logical OR gives the right value, which is the input.

```

Unfortunately, since dividing by zero isn't actually an error in Jelly, I cannot use that. Although, it wouldn't save me any bytes: `%2C:@` is the same length.

# Answer
> 4 votes
# A0A0, 161 146 138 bytes

```
I0A10A6V0
G-1G-1A5G0D2A0
A8O0
G1
A0A0
A0C3G1G1A0
A0L1S2M4
A0A1G-3G-3A0
G-3

G-1G-1

A0A0
C3G1G1A0C3G1G1A0
G-10A0G-10A0
A0A1G-3G-3A0
G-3

```

Since A0A0 does not have a modulo, or division, this uses repeated subtraction by 2 to get down to either a 0 or 1. If 1, the number is odd, if 0 the number is even.

```
I0  A10 A6 V0
G-1 G-1 A5 G0 D2 A0
A8  O0

```

Reads a number from the input `I0` and distributes the operand over two other lines. `A5 G0 D2 A0` completes the loop below in which we inserted the operand and `A8 O0` finishes the print function.

```
A0  A0
A0  C3 G1  G1  A0
A0  L1 S2  M4  V0 G0 D2 A0
A0  A1 G-3 G-3 A0
G-3

```

With the inserted code executed before this completes a loop that compares the operand to 1 and jumps to 1 (operand is greater than 1), 0 (operand is equal to 1) or -1 (operand is less than one) lines down depending on the comparison. We add 2 to this and multiple it by 4, to get the offsets 12, 8 and 4.

```
A0   A0
C3   G1 G1   A0  C3 G1 G1 A0
G-10 A0 G-10 A0
A0   A1 G-3  G-3 A0
G-3

```

This is a loop located 12 lines down, executed when the operand is 2 or more, to jump back up to the repeated subtraction loop. It's padded with no-ops `G1`, since the loop must have three instructions or more to work.

At offset 8 is nothing, to stop the program.

At offset 4 is the code `A6 V0 O0`. The `A6` is a leftover from copying, but the last two print the initial value that was entered.

Edit: forgot to mention, but A0A0 has no errors or exceptions, so this only halts.

Edit 2: Optimized by 15 bytes. I misunderstood the default loop template I make use of in the code. I was under the impression that the amount of G1 and G-3 instructions on line 2 and 4 of the loop resp. needed to match the amount of instructions inside the loop. This is not the case, you only need two of them (although more also work, as long as each line has an equal amount of them). This change removes these extra instructions.

Edit 3: Optimized by 8 bytes. Because of edit two, it turns out that there's actually no minimum of three instructions in the loop. This allows us to drop four instructions (not two, since the loop at the bottom is partially evaluated), totalling eight bytes. I've also added a link to the language page in the post, since that was not present.

# Answer
> 4 votes
# R, ~~20~~ 19 bytes

```
(x=scan())[[!x%%2]]

```

Try it online!

# R 4.1, ~~15~~ 14 bytes

```
\(x)x[[!x%%2]]

```

Takes advantage of the fact that an R numeric is automatically a vector.

-1 byte by using a different indexing error due to Dominic van Essen.

# Answer
> 4 votes
# \>\<\>, 7 bytes

```
:2%?Cn;

```

The input should be put onto the stack using the `-v` command-line argument.

Try it even!
Try it odd!

---

### Explanation:

Initially, the stack contains the input number, \\$ n \\$.

* `:` duplicates the top of stack: \[\\$n\\$, \\$n\\$\]
* `2` pushes \\$2\\$ onto stack: \[\\$n\\$, \\$n\\$, \\$2\\$\]
* `%` pops two values and pushes their modulo: \[\\$n\\$, \\$n \\% 2\\$\]
* `?` pops the top value, and if it is \\$0\\$, the next instruction is skipped: \[\\$n\\$\]

If \\$n \\% 2 \neq 0\\$:

* `C` is not a valid instruction, so the program crashes.

If \\$n \\% 2 = 0\\$:

* `n` pops off the top value (\\$n\\$) and prints it: \[\]
* `;` terminates the program.

# Answer
> 4 votes
# Whitespace, 44 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
S _Duplicate_input][S S S T S N
_Push_2][T  S T T   _Modulo][N
T   S N
_If_0_Jump_to_Label_EVEN][N
S N
S N
_Jump_to_nonexistent_Label][N
S S N
_Create_Label_Even][T   N
S T _Print_as_integer]

```

Letters S (space), T (tab), and N (new-line) added as highlighting only. \[...\_some\_action\] added as explanation only.

**Try it online** (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer input = STDIN as integer
Integer temp = input modulo-2
If (temp == 0):
  Go to label EVEN
Go to nonexistent label (causing an error)

Label EVEN:
  Print input as integer
  (also shows an error: no exit defined; could be prevented by adding three trailing newlines)

```

# Answer
> 4 votes
## \<\>^v, 10 bytes

```
2,tT%1=VT;

```

##### Explanation

```
2,tT%1=VT;

2          Push 2 to the stack
 ,         Read number from stdin
  t        Pop stack and store into variable `t`
   T       Push the value of the variable `t` on the stack
    %      Modulo top of the stack by second element of stack
     1     Push 1
      =    Execute next instruction only if top 2 elements of the stack are equal
       V   Access variable V, which is undefined and cannot be set because its setter is a keyword (throws error)
        T  Push value of variable `t` onto stack
         ; Print top of stack

```

It tests if the number entered modulo 2 returns 1, if so (odd) it tries to access an undefined variable, so that throws an error and exits. If the modulo result is 0 (even), it pushes the number (stored in a variable), and then prints the top of the stack.

online link (the `>` is the input prompt, it is not an output of the program)

# Answer
> 4 votes
# Haskell, 12 bytes

```
f x|even x=x

```

Try it online!

# Answer
> 4 votes
# Brachylog, ~~7~~ 6 bytes

```
./₂ℕ∨ị

```

Try it online!

### Explanation

Raising up an error in Brachylog is surprisingly difficult (outside of transpilation errors obviously): in general in declarative logic programming it is better for predicates to fail ("return" false) rather than to throw errors (which has side-effects). Many things that you would expect to error don’t error, they simply don’t succeed to allow backtracking.

The simplest way to raise an error I thought about is to force computation (i.e. use floating point arithmetic, not constraint integer arithmetic) of something undefined: computing `ln(0)`.

@UnrelatedString found a 1 byte way to error: trying to cast a string to an integer, when the input string is a free variable.

```
.             Input = Output
 /₂           Divide it by 2
   ℕ          It must result in a non-negative integer
     ∨        If all that fails
      ị       Try to cast a free variable from string to int

```

# Answer
> 3 votes
# Python 3, 31 23 22 bytes

```
lambda x:x&1and a or x

```

Try it online!

Very simple answer, if the number is odd it just tries to check the value of an undefined variable.

*-8 bytes!* thanks to @Wasif

*-1 byte* due to replacing if .. else with and..or

# Answer
> 3 votes
# Rattle, 5 bytes

```
|b%[0

```

Try it Online!

Explanation:

```
|       take input
 b      add to print buffer
  %     modulo (mod 2 by default)
   [0   the first half of an if statement checking whether the answer is 0

```

Why this works: If the input is even, the result of `%` is 0 so the if statement is used. The if statement is empty however so nothing happens (and the print buffer is printed implicitly). If the input is odd, the result of `%` is not 0, so the interpreter will keep skipping forward looking for a closing `]` which is not to be found (the language will try to close the bracket from the if statement if it's not allowed to enter the if statement), resulting in an error.

# Old best:

# Rattle, <sup>~~8~~</sup> 7 bytes

```
|b%[1{]

```

Try it online!

# Explanation

```
|            takes the user's input
 b           adds this input to a print buffer
  %          checks to see if this value is odd (mod 2 is default)
   [1 ]      if the resulting value is 1, the code in this if statement executes
     {       this is an unsupported character, so it throws an exception
             buffer gets printed implicitly if an error was not thrown

```

# Note

Technically, this code could be reduced to 6 bytes by removing the `]` from the end.

# Answer
> 3 votes
# Go, 79 bytes

```
package main
import."fmt"
func main(){a:=[]int{0}
Scan(&a[0])
print(a[a[0]%2])}

```

# Answer
> 3 votes
# TI-Basic, <sup>~~9~~</sup> 6 bytes

```
sum(dim(identity(Ans/2

```

Tries to create a `Ans/2`-size identity matrix, which will fail for odd numbers

It will also fails for big-ish numbers depending on the available RAM

# Answer
> 2 votes
# Scala, 12 bytes

```
i=>i/(i+1&1)

```

Try it online!

# Answer
> 2 votes
# GNU-APL, 9 bytes

```
{⍵÷2⊤⍵+1}

```

The above function divdes the given number n with (n+1) mod 2.

Samples for 2 and 3

```
      {⍵÷2⊤⍵+1} 2
2
      {⍵÷2⊤⍵+1} 3
DOMAIN ERROR
λ1[1]  λ←⍵÷2⊤⍵+1

```

TIO in ngn/apl.

# Answer
> 2 votes
# **BQN**, 7 6 bytes<sup>SBCS</sup>

```
¯2⥊⍟|⊢

```

Try it here.

How it works:

```
¯2⥊⍟|⊢
  ⥊     # reshape (this can be any function that is not dyadically invertible)
   ⍟    # power modifier (⍟ applies ,  number of times)
¯2  |⊢  # input mod ¯2, gives 0 if even, ¯1 if odd.

```

`⍟0` is just equivalent to the identity function so it returns the input, and `⍟¯1` calls the inverse of  1 time, but since  can't be inverted it gives an error.

---

## 7 Byte solution:

```
⊢⊣·!2|¬

```

Try it here.

How it works:

```
⊢⊣·!2|¬
      ¬  # not (in BQN not(x) is extended to 1-x)
    2|   # mod 2
  ·!     # assert (throws an error if not 1)
⊢⊣       # return the input

```

# Answer
> 2 votes
# Racket, 29 bytes

```
(λ(x)(/ x(modulo(add1 x)2)))

```

Try it online!

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 14 bytes

```
a=>a%2<1?a:a/0

a=>                 # Function taking a
   a%2<1            # Boolean which is true if a is even
        ?a          # If true return a
          :a/0      # If false return a/0 which errors

```

Try it online!

# Answer
> 2 votes
# Starry, 18 bytes

```
, +       +    *'.

```

```
0,    push input
1+    duplicate
7+    push 2
4*    modulo
0'    jump to label 0 if top is non-zero
0.    print top

```

If the input mod 2 is non-zero (1) it attempts to jump to a label that doesn't exist, so it throws an error. Otherwise it reaches the end and prints the number.

Try it online!

# Answer
> 2 votes
# Commodore BASIC (C64/THEC64, PET, C128, VIC-20, C16/+4) - 18 14 BASIC bytes used \<- invalid entries (now removed) - 25 19 17 BASIC bytes

```
0INPUTN:ONNAND1GOTO1:PRINTN

```

It takes any numeric input and logically ANDs it with 1; Therefore for every odd number, this is `1` otherwise it is `0`. This value is passed to the `ON...GOTO` command. Where this is zero, it passes through to `PRINT N` and the program exits gracefully. Where this value is one, it will branch to line `1` which is not there, and therefore it reports an `?UNDEF'D STATEMENT ERROR IN 0`.

The old entry did not output any valid number, and so was removed. It was something like this:

```
0INPUTN:N=NAND1:IFNTHENX

```

# Answer
> 2 votes
# Excel, 14 bytes

```
=A1/ISEVEN(A1)

```

Input is in the cell `A1`. The formula can go anywhere else.

`ISEVEN()` is a built-in that returns `TRUE` or `FALSE`. When you perform a math operation (like dividing), Excel treats `TRUE` as `1` and `FALSE` as `0`. So odd numbers will try to divide by zero and return an error.

# Answer
> 2 votes
# Python 3, 21 bytes

```
lambda x:x//((x+1)%2)

```

Try it online!

# Answer
> 2 votes
# ///, 12 bytes

```
/??/!!//?/?/

```

Try it online!

The `///` language is Turing complete, yet only has one command: a simple `/find/replace/`. No special characters except the forward and back slashes. Each `/find/replace/` loops until it can no more, before moving onto the next. In `///`, the input is appended to the end of the program. The link places the input in the footer.

This program uses unary to represent numbers, taking input with `?` and returning output with `!`.

```
/??/!!/    Replaces all pairs of '?', with pairs of '!'
/?/?/      Replaces any '?' left with itself, creating an infinite loop

```

On evens, all questions are replaced with exclamations in the first pattern, and the program terminates with as many exclamations as it had questions. The same number is returned in unary.

On odds, after the first pattern there is one question mark left. This gets replaced with itself ad infinitum until TIO times out after 60 seconds.

There's technically no consensus that this counts as an error, but I'm counting TIO as the implementation here. Otherwise, I can certainly write another implementation that times out, or that uses recursion to eventually stack overflow.

# Answer
> 2 votes
# *Acc!!*, 103 bytes

```
N
Count i while _%60/48 {
_*60+N
Count j while 10/(_%60)*(i-j+1) {
Write _/60^(i-j+1)%60/(1-_/60%2)
}
}

```

Dies with a division-by-zero error if the input is odd. Try it online!

### Explanation

We start with a loop that reads digits into the accumulator until hitting a newline:

```
N
Count i while _%60/48 {
_*60+N
}

```

At the end of this loop, the accumulator can be read as a base-60 number whose digits are the entered characters' ASCII codes (the last one being 10 for newline). The loop variable `i` is one less than the number of digits in the input number. We need to know the length of the number to output the digits in order; since `i` goes out of scope as soon as its loop exits, we'll need to nest the output loop inside the input loop.

Naively, we could output the digits like so:

```
Count j while i-j+1 {
Write _/60^(i-j+1)%60
}

```

But we only want this loop to activate when we've just read a newline; so we multiply the condition by `10/(_%60)`, which is `1` when the last character read has a code of 10 (or below) and `0` when it has a code above 10:

```
Count j while 10/(_%60)*(i-j+1) {

```

Finally, we need an error when the input number is odd. This is the case if the final digit's character code (`_/60%60`) is odd; `1-_/60%2` will give `0` for odd and `1` for even. Then we can simply divide the output expression by this quantity to get the desired error/no-op behaviors:

```
Write _/60^(i-j+1)%60/(1-_/60%2)

```

# Answer
> 2 votes
# KonamiCode, 132 bytes

`>>>>(^^)v(>)>(^)v(>)L(>)>(^)v((>))>(^^)S(^)A(^^)v(^)A(^>^)L(^^)v(>)B(^^^)L(^^^)L(^>^)>(>)S((^))>(^)B(>)>(^^)S(>)A(^>)>(^>)<<L(^>)<<<`

This is basically identical to my answer here, but with a bit of code on the end that causes an InvalidMemoryIndexError if the number is odd.

# Answer
> 2 votes
# Perl 5, 9 bytes

```
$_%2&&die

```

Try it online!

# Answer
> 2 votes
# AsciiDots,~~41~~ 35 bytes

```
.&#$--\
*#1-*[-]/2#*.
\#?{+}*{%}[/]

```

Try it online!

# Answer
> 2 votes
# Python 3, 15 Bytes

```
print([n][n%2])

```

# Answer
> 2 votes
# Desmos, ~~30~~ ~~29~~ ~~28~~ 25 bytes

```
f(n)=[1...mod(n,2)8!][1]n

```

A lot of stuff that I tried just gives `undefined` instead of erroring out, but I finally found something that worked.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# C, 57 bytes

```
main(c,v)char**v;{c=atoi(1[v]);printf("%d",(c%2)?0/0:c);}

```

Exploits the ternary conditional to divide by zero (fastest way of causing an error?) if the first argument isn't even. Also abuses the argc variable to store the number.

*Note: To compile using LLVM Clang, use flag `-std=c89`. However, Clang-compiled versions won't just go though with attempting to divide by zero. Sad.*

A longer one (works with gcc and clang):

```
main(c,v)char**v;{c=atoi(1[v]);printf("%d",(c%2)?v[9999]:c);}

```

Attempts to access memory outside the program's bounds when given an odd number. Try removing some 9s at the cost of making the likelihood of accessing memory outside the program's bounds smaller. Works with three 9s in TIO.

Yes, I know that `atoi` isn't exactly good, but it's nice and short.

# Answer
> 2 votes
# Minecraft Command Blocks, 288 bytes

The commands in command blocks from left to right:

```
scoreboard objectives add n dummy
scoreboard players set n n <Input>
scoreboard players operation s n = n n
scoreboard players set 2 n 2
scoreboard players operation n n %= 2 n
execute if score n n matches 0 run tellraw @a {"score":{"name":"s","objective":"n"}}
execute if score n n matches 1 run setblock ~ ~ ~1 redstone_block
e

```

I didn't count the second command block which sets the input. If it's counted the total is **315** bytes plus the length of the number.

## Explanation

`scoreboard objectives add n dummy` creates a scoreboard objective named n. Scoreboard objectives are a way to store numbers similar to variables. Each objective can have an infinite number of variables associated with it, which are accessed like `<name> <objective>`. So `s n` would refer to the variable named `s` in the objective `n`. All the variables in this program are in the objective n.

`scoreboard players set n n <Input>` sets n to the input.

`scoreboard players operation s n = n n` copies the value of n to s. This is required because scoreboard operations overwrite the original value.

`scoreboard players set 2 n 2` sets the value of the variable 2 to 2. This is required because scoreboard operations can only be done with two variables, not a variable and a number.

`scoreboard players operation n n %= 2 n` modulos n by 2.

`execute if score n n matches 0 run tellraw @a {"score":{"name":"s","objective":"n"}}` prints the value of s (which was set to n) if n is 0, which indicates the number was even.

`execute if score n n matches 1 run setblock ~ ~ ~1 redstone_block` sets the block to the right of the command block to a redstone block if n is 1, indicating the number is odd. This triggers the last command block.

`e` is an invalid command, which throws an error, as seen here.

# Answer
> 1 votes
# Python 3, 62 bytes

```
i=int(input())
if i%2==0:
    print(i)
else:
    raise Exception('')

```

Try it online!

# Python 3, 41 bytes thanks to @hyper-neutrino

```
i=int(input())
if i%2<1:print(i)
else:1/0

```

Try it online 2!

# Python 3, 37 bytes thanks to @user

```
i=int(input())
if i%2:g
else:print(i)

```

Try it online 3!

# Answer
> 1 votes
# Charcoal, 6 bytes

```
Ｉ§0#Ｎθ

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｉ§0#Ｎ

```

Cyclically (i.e. modulo 2) index into the string `0#` using the input as an integer, and try to cast that character into an integer. This throws a ValueError for `#`.

```
θ

```

Print the input.

# Answer
> 1 votes
# Pip, 6 bytes

```
VkX%aa

```

Try it here! Or, here's the 7-byte equivalent in Pip Classic: Try it online!

### Explanation

```
    a   Command-line argument
   %    Mod 2: 0 if even, 1 if odd
 kX     Repeat the string ", " that many times
V       Eval
        If even, eval empty string (no-op); if odd, eval ", " (parse error)
     a  If there wasn't an error, autoprint the command-line argument

```

# Answer
> 1 votes
# C (clang), ~~74~~ 45 bytes

```
main(i){scanf("%i",&i);printf("%i",i/=~i&1);}

```

Try it online!

Takes an `int` for input, then uses an if-else statement to choose if the number is odd or even. If the number's odd, it doesn't output anything, but shows the error anyway. Even numbers display the error, but at least the number is inputted.

Thanks to ceilingcat, with the help of Olivier Grégoire, for golfing 29 bytes.

# Answer
> 1 votes
# Zsh, 16 bytes

```
<<<$1>0
<$[$1%2]

```

Try it online!

# Answer
> 1 votes
# Julia 1.0, ~~11~~ 10 bytes

```
n->n[~n&1]

```

Try it online!

Numbers can be indexed by one (`4[1] == 4`) but any other number will throw an error (`0` here when `n` is odd)

-1 byte thanks to Olivier Grégoire's answer

# Answer
> 1 votes
# Coconut, 10 bytes

```
n->n<<n%-2

```

Try it online!

Coconut port of @xnor's trick

# Answer
> 1 votes
# Lua, 27 bytes

```
print(...%2<1 and...or o())

```

Try it online!

Not very creative or tricky. Thanks to JS answer for reminding me about ternary operator.

# Answer
> 1 votes
# COBOL(GNU), 252 bytes

```
IDENTIFICATION DIVISION.PROGRAM-ID.A.DATA DIVISION.WORKING-STORAGE SECTION.
     01 A PIC 9(2).
     01 R PIC 9(2).
     01 Q PIC 9(2).
PROCEDURE DIVISION.ACCEPT A.DIVIDE A BY 2 GIVING R REMAINDER Q.IF Q IS EQUAL TO 0
DISPLAY A
ELSE
STOP RUN.
STOP RUN.

```

Please let me know if I can golf this down even more. Don't have time to explain this now.

https://tio.run/##bY4xbwIxDIX3@xUey5AI2DqaxEQWR5JzclSMLQIWBFKrSv31Tc3SY8DT82f5vXe4fdwu5nz9bo09xcprdlg5RfC846LCZklBcGvYW7QeK06ntyQbjsGUmgQDQSF3/7Ud3Ge@AITMDl5flrOJyRM2PDDNc@RHoSkHnaNcQeOVeFLb1R6WEHSLQQ2FtsjRk8Bgea1uXICGEXuoCead55J73AN21BfqtG0GGbXmv2rt93C6vJ@/mvlp5vR5PP4B

# Answer
> 1 votes
# PHP, 16 bytes

```
1/!($argv[1]%2);

```

Divides 1 by opposite the input mod 2. Throws a division by zero error upon odd numbered inputs.

Try it online!

# Answer
> 1 votes
# Grok, 12 bytes

```
:Y2%}_
qzp h

```

Try it Online!

Copies the input number, and if `n%2 = 0`, goes down and to the left, prints, and terminates. If `n%2 = 1`, then it hits `_`, which errors, since it is an invalid command.

# Answer
> 1 votes
# Clojure,20 19 bytes

#(/ %(- 1(mod % 2)))

```
#(/ %(mod(inc %)2))

```

Try it online!

# Answer
> 1 votes
# MathGolf, 3 bytes

```
¥┌/

```

Try it online.

**Explanation:**

```
¥    # Modulo-2 the (implicit) input-integer
 ┌   # Invert the boolean (0 becomes 1 and vice-versa)
  /  # Integer-divide the (implicit) input-integer by this
     # (which causes division by zero errors)
     # (after which the entire stack is output implicitly)

```

# Answer
> 1 votes
J (Jsoftware.com), 7 bytes

```
   f=: 13 : '(2|y){y' NB define function f
   f                  NB. display f 7 bytes
   =============> this is the function, it is seven characters
     ] { ~ 2 | ]
   <=============
                  NB. spaces optional
                  NB. ..and shown for clarity

   f 2                NB. test with even number
2
   f 3                NB. odd number throws error
    |index error: f
    |       f 3

NB. 2|y finds n mod 2 => 1 odd or 0 even
NB. { use result as index into input
NB. there is only one input so 1 throws error

```

# Answer
> 1 votes
# Python 3, 18 bytes

```
lambda n:n/(n%2<1)

```

Try it online!

# Answer
> 1 votes
# Standard ML (Moscow ML), 21 bytes

```
fun$0=0| $x=2+ $(x-2)

```

Defines a function `$ : int -> int` that throws an `Out_of_memory` exception for odd numbers. Requires the Moscow ML interpreter.

```
- fun$0=0| $x=2+ $(x-2);
> val $ = fn : int -> int
- $ 4;
> val it = 4 : int
- $ 3;
! Uncaught exception:
! Out_of_memory

```

---

## Standard ML, 22 bytes

```
fn x=>x div(1-x mod 2)

```

Try it online!

Anonymous function that throws a `Div` exception and works in all implementations.

---

Just for fun, here are some other exceptions:

### `Match`, 24 bytes

```
fn x=>(fn 0=>x)(x mod 2)

```

Try it online!

### `Bind`, 29 bytes

```
fn$ =>let val 0= $mod 2in$end

```

Try it online!

# Answer
> 1 votes
# Ruby, 27 bytes

```
n=gets.to_i;p(n%2==0?n:n/0)
```

Attempt This Online!

# Answer
> 1 votes
# Exceptionally, 10 bytes

```
GI}n%2=0Pn

```

Attempt This Online!

### Explanation

```
GI}n%2=0Pn
G           Get a line of stdin
 I          Convert to integer
  }n        Store a copy of that value in n
    %2      Mod 2
      =0    Assert equal zero; if it's not, throws an error
        Pn  Otherwise, print n

```

If the program reaches `Pn` successfully, it loops back to the beginning, tries to read another line of input, and dies when there is no line to read.

# Answer
> 1 votes
# Python 3, 29 bytes (full program)

```
a=int(input())
print(a<<a%-2)

```

Explanation:

```
a=int(input()) # usual input line
         a%-2  # even numbers map to 0, odd numbers map to -1
      a<<      # part which triggers error (can't shift negative times)
print(       ) # output if no error

```

Try it online!

# Answer
> 1 votes
# Re:direction, 11 bytes

```
++>>
 +
v
<

```

Try it online!

The input number *n* is represented in the queue as *n* `>`s followed by a `v`. The loop in the first line removes two `>`s from the front of the queue (with the `+`s) and adds them back to the back of the queue (with the `>`s), exiting once less than two remain.

An odd number goes down from the second `+` and hits the `+` below it, which consumes the `>`s left in the queue, coming back to itself each time, until the queue is empty, at which point it produces an error.

An even number goes down from the first `+` with *n* `>`s in the queue, adds a `v` to re-create the representation of `n`, and then hits the `<`, which is ignored in output and points to itself to end the program.

# Answer
> 1 votes
# Pyt, 5 bytes

```
Đ⁺2%/

```

Try it online!

The code tries to do \\${n\over(n+1)\\!\\!\\!\\!\mod\\!\\! 2}\\$, which throws a division-by-zero error when n is odd.

# Answer
> 1 votes
# K (ngn/k), 6 bytes

```
(2!)0/

```

Try it online!

Sets up a while-loop, testing if `2!` (i.e., mod by 2) returns a truthy value when run on the input/current value. If a truthy value is returned, it *then* attempts to calculate `0@x`, which fails with a `'rank` error, as atoms cannot be indexed. If `(2!)` returns a falsey value on the original input, nothing else is run, and the original value is returned unchanged.

# Answer
> 0 votes
# Ruby, 12 bytes

```
->n{n/=1&~n}

```

Try it online!

# Answer
> 0 votes
# Python 3, 19 bytes

```
lambda x:x//(1-x%2)

```

If the number is even, `x%2` is 0 and `1-x%2` is 1, so this evaluates to `x//1` which is simply `x`, since floor dividing by 1 gives the original integer.
However, if it is odd, `x%2` is 1, `1-x%2` is 0, and this evaluates to `x//0` which raises a `ZeroDivisionError`.

# Answer
> 0 votes
# Python 3, 51 bytes

```
i=input()
if int(i)&1:raise Exception
else:print(i)

```

Try it online

# Answer
> 0 votes
# Clarion, 91 bytes

In Clarion, calling a function that is prototyped to return a parameter, but the body of said function does not explicitly return anything causes a runtime exception. I think I might be cheating slightly by not explicitly halting the program, but the dialog that shows after the exception occurs has a "Continue" or "Exit" button, and if you hit continue it will re-trigger the exception, giving you no choice but to terminate anyway.

The input is given as the first command-line parameter.

It's not particularly short compared to the other incredible answers here, but I like Clarion :)

```
Program
 Map;f,?.
Code
 i#=Command(1);If i#%2=0;Stop(i#);Else;x#=f().
f Function
 Code

```

# Answer
> 0 votes
## PostScript, 31 bytes

```
.runstdin dup 2 mod 1 eq{x}if =

```

Requires ghostscript for `.runstdin`; raises `/undefined in x` on odd input.

# Answer
> 0 votes
# Nim, 70 bytes

```
proc f(n:int)=
  if n mod 2==1:raise Exception.newException""
  echo.n
```

Attempt This Online!

The first solution that came to mind. Rather run-of-the-mill.

# Answer
> 0 votes
# Arturo, 16 bytes

```
$[n][n/(n+1)%2n]

```

Try it

```
$[n][             ; a function taking an argument n
    n /           ; n divided by...
    (n + 1) % 2   ; n plus one modulo two  (error here if n is odd)
    n             ; push n
]                 ; end function, implicit return

```

# Answer
> 0 votes
# Thunno (older versions only), \\$ 4 \log\_{256}(96) \approx \\$ 3.29 bytes

```
2%?J

```

This uses a bug which was fixed in v1.1.1. ATO has v1.2.1 so it will not work there.

#### Explanation

* `2%` mods the input by 2. An even number will result in `0` and an odd number will result in `1`.
* `?` is an `if` statement. If the top of the stack is truthy (`1`), run the following code:
    + `J` means `''.join` and expects a list. If it doesn't get a list, it throws an error.
    + Therefore, if the input was odd, it will throw an error.
* If it was even, it will just pass through and output whatever was input

#### Screenshots

# Answer
> 0 votes
# YASEPL, 11 bytes

```
=a'=b$a%@!<

```

explanation:

```
=a'=b$a%@!<              packed
=a'                      get user input and set it to A
   =b$a                  create variable B and set it to content of A
       %                 B = B mod 2
        @                if B is equal to 1, then go to point 1 (point 1 does not exist so it errors if its true)
         !<              else, print A

```

# Answer
> 0 votes
# Vyxal 3, 3 bytes

```
ḃ[x

```

Try it Online!

If the bit parity is 0, then it just outputs the number. Otherwise it gives a "too many recursions" error

# Answer
> 0 votes
# Lua, 26 bytes

### Main code

```
print(0==n%2 and n or -m)

```

Try it online!

### TIO Header

```
-- To read input
n = io.read()

```

---

## Explanation

We read in our input via `io.read()` into a variable `n`.

```
n = io.read()

```

we then write a ternary statement inside of the `print` function to test whether `n` is even or odd. If `n` is even, we pass it over to `print`, otherwise we take the negation of a `nil` global variable to throw an error.

```
print (0 == n%2 and n or -m)

```

Note that ternary statements in Lua come in the form of `(condition and true-expr or false-expr)`.

# Answer
> 0 votes
# Swift, 19 bytes

```
let f={$0/(1-$0%2)}

```

If `$0` (the implicit closure parameter) is even, `$0 % 2` is `0`, `1 - 0` is 1, and `$0 / 1` is the original value. If `$0` is odd, `$0 % 2` is `1`, `1 - 1` is `0`, and `$0 / 0` ends up calling `assertionFailure(_:file:line:)`.

---
Tags: code-golf, math, decision-problem, integer, error-message
---