# Swap the parity

Given a positive integer n, output n+1 if n is odd, and output n-1 if n is even.

# Input

A positive integer. You may assume that the integer is within the handling capability of the language.

# Output

A positive integer, specified above.

input output
1      2
2      1
3      4
4      3
5      6
6      5
7      8
8      7
313    314
314    313

# Scoring

This is , so shortest answer in bytes wins.

Standard loopholes apply.

# References

• May we take input as unary? – Kritixi Lithos May 4 '17 at 10:12
• This would be, surprisingly, a lot easier if it was the other way around in some languages – MildlyMilquetoast May 5 '17 at 17:41
• @MistahFiggins That's well known enough that I'm pretty sure OP did it like this on purpose. – Ørjan Johansen May 5 '17 at 20:51

# C, 20 bytes

f(x){return-(-x^1);}
• @LeakyNun I am not writing a function lacking a return statement. – feersum May 4 '17 at 9:08
• @EriktheOutgolfer No. Nope. Nuh-uh. No. – feersum May 4 '17 at 9:24
• @Sisyphus But this is code-golf, and it works on my TIO link, so it's valid. – Erik the Outgolfer May 4 '17 at 10:07
• @EriktheOutgolfer What I am saying is that your statement ("assigning to the first argument is equivalent to a return statement" ) is factually incorrect. Whether such code may generate a working answer under certain circumstances is another question (which I have addressed in my first comment by stating that I plan not to post any such code). – feersum May 4 '17 at 10:16
• @EriktheOutgolfer If an answer relies on implementation specific behavior, it should specify an implementation. This answer doesn't, so that code would be invalid. – Sisyphus May 4 '17 at 10:44

## Stack Cats, 3 + 3 (-n) = 6 bytes

-*-

Try it online!

Needs the -n flag to work with numeric input and output.

### Explanation

Stack Cats is usually far from competitive, because of its limited set of commands (all of which are injections, and most of which are involutions) and because every program needs to have mirror symmetry. However, one of the involutions is to toggle the least-significant bit of a number, and we can offset the value with unary negation which also exists. Luckily, that gives us a symmetric program, so we don't need to worry about anything else:

-   Multiply the input by -1.
*   Toggle the least significant bit of the value (i.e. take it XOR 1).
-   Multiply the result by -1.

Input and output are implicit at the beginning and end of the program, because taking input and producing output is not a reversible operation, so they can't be commands.

• Are flags always counted with the additional space, I don't think I've seen other answers using flags (like Perl) do that? EDIT: Ok nvm, found the relevant meta post. "I count those as a difference in character count to the shortest equivalent invocation without them." ... "perl -nle 'stuff' is 2 characters more than perl -e 'stuff', so it counts for 2 more characters". So (space)-n is 3 bytes more than without the flag. – Kevin Cruijssen May 4 '17 at 9:29
• @KevinCruijssen It depends on how many bytes you actually need to add to a usual invocation. In Perl and many other production languages, you can invoke the code with -e "code" and then insert additional flags before the e, e.g. -pe "code". Then the -p flag is only one byte. However, Stack Cats has no such -e argument, so you always need to add the full <sp>-n to the command, and hence it's three bytes. – Martin Ender May 4 '17 at 9:31

# x86 Assembly, 9 bytes (for competing entry)

Everyone who is attempting this challenge in high-level languages is missing out on the real fun of manipulating raw bits. There are so many subtle variations on ways to do this, it's insane—and a lot of fun to think about. Here are a few solutions that I devised in 32-bit x86 assembly language.

I apologize in advance that this isn't the typical code-golf answer. I'm going to ramble a lot about the thought process of iterative optimization (for size). Hopefully that's interesting and educational to a larger audience, but if you're the TL;DR type, I won't be offended if you skip to the end.

The obvious and efficient solution is to test whether the value is odd or even (which can be done efficiently by looking at the least-significant bit), and then select between n+1 or n−1 accordingly. Assuming that the input is passed as a parameter in the ECX register, and the result is returned in the EAX register, we get the following function:

F6 C1 01  |  test  cl, 1                      ; test last bit to see if odd or even
8D 41 01  |  lea   eax, DWORD PTR [ecx + 1]   ; set EAX to n+1 (without clobbering flags)
8D 49 FF  |  lea   ecx, DWORD PTR [ecx - 1]   ; set ECX to n-1 (without clobbering flags)
0F 44 C1  |  cmovz eax, ecx                   ; move in different result if input was even
C3        |  ret

(13 bytes)

But for code-golf purposes, those LEA instructions aren't great, since they take 3 bytes to encode. A simple DECrement of ECX would be much shorter (only one byte), but this affects flags, so we have to be a bit clever in how we arrange the code. We can do the decrement first, and the odd/even test second, but then we have to invert the result of the odd/even test.

Also, we can change the conditional-move instruction to a branch, which may make the code run more slowly (depending on how predictable the branch is—if the input alternates inconsistently between odd and even, a branch will be slower; if there's a pattern, it will be faster), which will save us another byte.

In fact, with this revision, the entire operation can be done in-place, using only a single register. This is great if you're inlining this code somewhere (and chances are, you would be, since it's so short).

48     |  dec  eax          ; decrement first
A8 01  |  test al, 1        ; test last bit to see if odd or even
75 02  |  jnz  InputWasEven ; (decrement means test result is inverted)
40     |  inc  eax          ; undo the decrement...
40     |  inc  eax          ; ...and add 1
InputWasEven:                 ; (two 1-byte INCs are shorter than one 3-byte ADD with 2)

(inlined: 7 bytes; as a function: 10 bytes)

But what if you did want to make it a function? No standard calling convention uses the same register to pass parameters as it does for the return value, so you'd need to add a register-register MOV instruction to the beginning or end of the function. This has virtually no cost in speed, but it does add 2 bytes. (The RET instruction also adds a byte, and there is a some overhead introduced by the need to make and return from a function call, which means this is one example where inlining produces both a speed and size benefit, rather than just being a classic speed-for-space tradeoff.) In all, written as a function, this code bloats to 10 bytes.

What else can we do in 10 bytes? If we care at all about performance (at least, predictable performance), it would be nice to get rid of that branch. Here is a branchless, bit-twiddling solution that is the same size in bytes. The basic premise is simple: we use a bitwise XOR to flip the last bit, converting an odd value into an even one, and vice versa. But there is one niggle—for odd inputs, that gives us n-1, while for even inputs, it gives us n+1— exactly opposite of what we want. So, to fix that, we perform the operation on a negative value, effectively flipping the sign.

8B C1     |  mov eax, ecx   ; copy parameter (ECX) to return register (EAX)
|
F7 D8     |  neg eax        ; two's-complement negation
83 F0 01  |  xor eax, 1     ; XOR last bit to invert odd/even
F7 D8     |  neg eax        ; two's-complement negation
|
C3        |  ret            ; return from function

(inlined: 7 bytes; as a function: 10 bytes)

Pretty slick; it's hard to see how that can be improved upon. One thing catches my eye, though: those two 2-byte NEG instructions. Frankly, two bytes seems like one byte too many to encode a simple negation, but that's the instruction set we have to work with. Are there any workarounds? Sure! If we XOR by -2, we can replace the second NEGation with an INCrement:

8B C1     |  mov eax, ecx
|
F7 D8     |  neg eax
83 F0 FE  |  xor eax, -2
40        |  inc eax
|
C3        |  ret

(inlined: 6 bytes; as a function: 9 bytes)

Another one of the oddities of the x86 instruction set is the multipurpose LEA instruction, which can do a register-register move, a register-register addition, offsetting by a constant, and scaling all in a single instruction!

8B C1        |  mov eax, ecx
83 E0 01     |  and eax, 1        ; set EAX to 1 if even, or 0 if odd
8D 44 41 FF  |  lea eax, DWORD PTR [ecx + eax*2 - 1]
C3           |  ret

(10 bytes)

The AND instruction is like the TEST instruction we used previously, in that both do a bitwise-AND and set flags accordingly, but AND actually updates the destination operand. The LEA instruction then scales this by 2, adds the original input value, and decrements by 1. If the input value was odd, this subtracts 1 (2×0 − 1 = −1) from it; if the input value was even, this adds 1 (2×1 − 1 = 1) to it.

This is a very fast and efficient way to write the code, since much of the execution can be done in the front-end, but it doesn't buy us much in the way of bytes, since it takes so many to encode a complex LEA instruction. This version also doesn't work as well for inlining purposes, as it requires that the original input value be preserved as an input of the LEA instruction. So with this last optimization attempt, we've actually gone backwards, suggesting it might be time to stop.

Thus, for the final competing entry, we have a 9-byte function that takes the input value in the ECX register (a semi-standard register-based calling convention on 32-bit x86), and returns the result in the EAX register (as with all x86 calling conventions):

SwapParity PROC
8B C1         mov eax, ecx
F7 D8         neg eax
83 F0 FE      xor eax, -2
40            inc eax
C3            ret
SwapParity ENDP

Ready to assemble with MASM; call from C as:

extern int __fastcall SwapParity(int value);                 // MSVC
extern int __attribute__((fastcall)) SwapParity(int value);  // GNU
• Wouldn't just dec eax; xor eax, 1; inc eax work and save one byte more? – Ilmari Karonen May 5 '17 at 12:51

# Jelly, 3 bytes

-*ạ

Try it online!

Pseudocode: abs((-1)**n - n)

• I was actually planning to (ab)use -1. – Erik the Outgolfer May 4 '17 at 8:48
• Sorry for that. – Leaky Nun May 4 '17 at 8:48
• There isn't any sorry, well done! I didn't figure out how to do it quickly enough... – Erik the Outgolfer May 4 '17 at 8:50

# Python3, 20 18 bytes

lambda n:n-1+n%2*2

Pretty simple. First we calculate n-1 and decide whether to add 2 to it, or not.

If n is even --> n mod 2 will be 0, thus we'll add 2*0 to n-1, resulting in n-1.

If n is odd --> n mod 2 will be 1, thus we'll add 2*1 to n-1, resulting in n+1.

I prefer an explanation that I made with MS paint & a laptop touchpad...

# Python, 16 bytes

lambda x:-(-x^1)

Try it online!

• Brute forcing doesn't find any shorter solution using characters in "x+-012~|&^()*/%". – xnor May 4 '17 at 9:00
• @xnor Good thing I got it then! – sagiksp May 4 '17 at 9:02
• And it looks like there are no other same-length solutions except the trivial rearrangement -(1^-x). – xnor May 4 '17 at 9:18

# MATL, 7 bytes

Q:HePG)

This avoids any arithmetical operations. Try it online!

### Explanation

Consider input 4 as an example.

Q    % Implicit input. Add 1
% STACK: 5
:    % Range
% STACK: [1 2 3 4 5]
He   % Reshape with 2 rows in column-major order. Pads with a zero if needed
% STACK: [1 3 5;
2 4 0]
P    % Flip vertically
% STACK: [2 4 0;
1 3 5]
G    % Push input again
% STACK: [2 4 0;
1 3 5], 4
)    % Index, 1-based, in column major order. Implicitly display
% STACK: 3
• Nice! Like it ! – Stewie Griffin May 4 '17 at 9:00

# Braingolf v0.1, 11 10 bytes

.1>2,%?+:-

Try it online! (Second argument is the Braingolf code, third argument is the input)

Saved a byte thanks to Neil

First ever competing braingolf answer :D

Explanation:

.            Duplicate the top of the stack
1>          Push 1 to the bottom of the stack
2         Push 2 to stack
,%       Pop last 2 items, mod them and push result
?      If last item > 0
+     Add the 1 to the input
:    Else
-   Subtract the 1 from the input

No semicolon in code so print last item

# Braingolf v0.2, 9 bytes [non-competing]

.2%?1+:1-

Try it online! (Second argument is the Braingolf code, third argument is the input)

See above for explanation. Only difference is in Braingolf v0.2, the default behaviour of diadic operators, and the function of the , modifier, are reversed, meaning the 2 commas in the v0.1 answer are no longer needed.

However v0.2 was released after the challenge, so this one's non-competing

• Congratulations on your new language! – Leaky Nun May 4 '17 at 8:30
• Does .1<2,%?+:- do what I think it does? – Neil May 4 '17 at 9:31
• @Neil not quite, you'd need a comma before the - to make it perform the operation the correct way around, in which case it'd still be the same length as my answer – Skidsdev May 4 '17 at 9:33
• @Mayube I was expecting the < to rotate the 1 below the input, so that it would be in the correct place already. – Neil May 4 '17 at 9:34
• @Neil if the input is an even number, by the time it reaches the - the stack looks like this: [n,1] braingolf operators are reversed, so it would perform 1 - n, which would result in -(n-1), wheras the desired result is simply n-1 – Skidsdev May 4 '17 at 9:37

# Cubix, 10 9 bytes

cO1)I(//@

Try it online

### Explanation

Net version

c O
1 )
I ( / / @ . . .
. . . . . . . .
. .
. .

The executed characters are

I(1c)O@
I          Input
(         Decrement
1c       XOR with 1
)      Increment
O@    Output and exit

## Python, 68 bytes

lambda x:[m.floor(x-m.cos(m.pi*x)) for m in [__import__('math')]][0]

In the spirit of a unique approach. The following graph shows the function (with purple dots representing the first 10 cases). It should in theory be possible to construct a solution for this question based on most (all?) periodic functions (e.g. sin, tan, sec). In fact, substituting cos for sec in the code as is should work.

# PHP, 15 bytes

<?=-(-$argn^1); • How do I run this? I'm trying to test whether the ; is required, and have tried using a .php file and also echoing directly into php (php7 cli.) Each time I'm told that$argn is an undefined variable. – Andrakis May 4 '17 at 11:51
• @Andrakis With the F flag and a pipeline: echo 42 | php -F script.php. – user63956 May 4 '17 at 13:36

# Javascript, 17 12 bytes

x=>x-(-1)**x

f=x=>x-(-1)**x;
<input id=i oninput=o.innerText=f(this.value) type=number><pre id=o>

# Another approach, 10 bytes stolen from the C answer (sssshhh)

x=>-(-x^1)

f=x=>-(-x^1)
<input id=i oninput=o.innerText=f(this.value) type=number><pre id=o>

• 1. you don't need to include the semicolon; 2. x=>x-(-1)**x – Leaky Nun May 4 '17 at 8:43
• Why the |0? Both solutions look as if they should automatically convert strings to numbers. (For the first solution, if you want to avoid decimals, use <input type=number>.) – Neil May 4 '17 at 9:27
• @Neil Thanks for notifying me! – Matthew Roh May 4 '17 at 9:28

# JavaScript (ES6), 141312 10 bytes

n=>-(-n^1)
• 1 byte saved thanks to Luke.
• 2 bytes saved by porting feersum's C solution. (If that's frowned upon, please let me know and I'll roll back to my previous solution below)

## Try It

f=
n=>-(-n^1)
<input id=i type=number><pre id=o>

n=>n-1+n%2*2

# Python, 20 bytes

lambda n:n+(n%2or-1)

n%2or-1 will return 1 if it's odd, but if it's even, n%2 is "false" (0), so it instead returns -1. Then we simply add that to n.

### Previous solution, 23 bytes

lambda n:[n-1,n+1][n%2]

n%2 calculates the remainder when n is divided by 2. If it's even, this returns 0, and element 0 in this list is n-1. If it's odd, this returns 1, and element 1 in this list is n+1.

• Use a lambda: lambda n:[n-1,n+1][n%2] – Leaky Nun May 4 '17 at 8:35
• Ah yes, so it was shorter in this case. Done, thanks! – numbermaniac May 4 '17 at 8:36

# Retina, 21 bytes

.+
$* ^11(?=(11)*$)

Try it online! My first Retina answer with two trailing newlines! Explanation: The first two lines convert from decimal to unary. The third and fourth lines subtract two from even numbers. The last line converts back to decimal, but adds one too.

(1^(

Try it online!

u%2!I(/+@O<

Try it online!

# Explanation

Net version:

u %
2 !
I ( / + @ O < .
. . . . . . . .
. .
. .

Characters are executed in following order:

I(2%!+O@
I        # Take a number as input
(       # Decrement it
2%     # Take the parity of the decremented number
# (0 if the input is odd, 1 if it's even)
!    # If that number is zero:
O  # Output the number
@ # Terminate the program

# Brain-Flak, 36 bytes

(({})(())){({}[()]<([{}])>)}{}({}{})

Try it online!

I'm personally really happy with this answer because it is a lot shorter than what I would deem a traditional method of solving this problem.

## Explanation

The first bit of code

(({})(()))

converts the stack from just n to

n + 1
1
n

Then while the top of the stack is non zero, we decrement it and flip the sign of the number under it

{({}[()]<([{}])>)}

The we remove the zero and add the two remaining numbers

{}({}{})

# Mathematica, 22 19 bytes

Saved 3 bytes thanks to Greg Martin!

#-1[-1][[#~Mod~2]]&

#+{-1,1}[[#~Mod~2+1]]&

Mathematica has the nice feature that operations such as arithmetic automatically thread over lists.

In this case, we take Mod[#,2] which will return 0 or 1, but we need to add 1 because Mathematica lists are 1-indexed. If it's even, this comes out to 1, so #-1 is returned. If it's odd, this comes out to 2, so #+1 is returned.

• You can save three bytes by abusing Mathematica's [[0]] capability: #-1[-1][[#~Mod~2]]&. – Greg Martin May 4 '17 at 18:34
• That's insane, never would've thought of that. Done, thanks! – numbermaniac May 5 '17 at 3:40

# Wise, 8 bytes

-::^~-^-

Try it online!

## Explanation

If this were the other way around, (decrement if odd, increment if even), it would be quite easy to do this.

We would just flip the last bit.

::^~-^

The fix here is that we flip the last bit while negative. The negative numbers are 1 off from the negation of the numbers ~ so this creates an offset resolving the problem.

So we just take out program and wrap it in -.

-::^~-^-

n->-(-n^1)

# Java 7, 34 28 bytes

int c(int n){return-(-n^1);}

Boring ports of @feersum's amazing C answer.
Try it here.

Java 8, 16 bytes

n->n%2<1?n-1:n+1

Java 7, 34 bytes

int c(int n){return--n%2>0?n:n+2;}

Explanation (of old Java 7 answer):

Try it here.

The answer above is a shorter variant of int c(int n){return n%2<1?n-1:n+1;} by getting rid of the space.

int c(int n){     // Method with integer parameter and integer return-type
return--n%2>0?  //  If n-1 mod-2 is 1:
n             //   Return n-1
:              //  Else:
n+2;          //   Return n+1
}                 // End of method

n ^1 n

Try it online!

# Python, 20 bytes

lambda n:n+(n&1)*2-1

## Befunge 93, 18 bytes

&:2%#v_1+.@
@.-1 <

I am not done golfing this yet (I hope).

• Golfing tips: Befunge 98 has the ability to use kv (or jv if it is strictly 1 or 0) instead of #v_. Also, if you are using Try it online (and I recommend it), you can end the program with another & (although it will take 60 seconds), so you can get rid of the @ on the first line if you use that. here is the full list of commands for Befunge-98, although they might not all be correctly implemented in TIO, like & ending the program instead of reversing on EOF. – MildlyMilquetoast May 5 '17 at 16:54
• Also, It looks like you're using befunge 93 instead of 98, which has fewer commands. You might want to fix your link name if it is indeed 93 and not 98 – MildlyMilquetoast May 5 '17 at 17:01
• @MistahFiggins, ah yes you are correct I was using 93. – Daniel May 5 '17 at 17:19

->n{-(-n^1)}

# R, 17 bytes

(n=scan())-(-1)^n

where n=scan() takes the digit value.

• I think you need -(-1)^n rather than +(-1)^n since we need to return n-1 if n is even – Giuseppe Jul 13 '17 at 18:25
• @Giuseppe oh, yes, of course, foolish mistake – Nutle Jul 13 '17 at 20:18

# Casio-Basic, 27 bytes

piecewise(mod(n,2),1,-1)+n

26 bytes for the function, +1 to enter n in the parameters box.

# C, 29 bytes

a(int b){return b%2?b+1:b-1;}

# Jelly, 4 bytes

‘’Ḃ?

Try it online!

• @LeakyNun thanks for testcases – Erik the Outgolfer May 4 '17 at 9:44

## Batch, 20 bytes

@cmd/cset/a"-(1^-%1)

Independently rediscovered @feersum's algorithm, honest!