30
\$\begingroup\$

Task

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.

Testcases

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

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

78 Answers 78

1
\$\begingroup\$

Groovy, 17 bytes

print x%2?x+1:x-1

Just substitute x for desired number. Try it online here -> https://tio.run/nexus/groovy and copy the code.

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

Befunge 93, 18 bytes

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

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

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$ May 5, 2017 at 16:54
  • \$\begingroup\$ 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 \$\endgroup\$ May 5, 2017 at 17:01
  • \$\begingroup\$ @MistahFiggins, ah yes you are correct I was using 93. \$\endgroup\$
    – Daniel
    May 5, 2017 at 17:19
1
\$\begingroup\$

Ruby, 12 bytes

->n{-(-n^1)}
\$\endgroup\$
1
\$\begingroup\$

Chip, 61 bytes

  * *
A~#-#a
B~#~#b
C~#~#c
D~#~#d
E~#~#e
F~#~#f
G~#~#g
H~#~#h

Try it online!

Since Chip natively handles only byte-sized integers, this solution reads in and writes out bytes. The TIO is set up to use the \x00 notation for this.

This Chip solution uses a straightforward approach where the columns are the operations, and the rows are for each bit:

Read in an octet
|Invert all bits
||Increment
|||Invert all bits except the lowest bit
||||Increment
|||||Output the octet
||||||

  * *
A~#-#a
B~#~#b
C~#~#c
D~#~#d
E~#~#e
F~#~#f
G~#~#g
H~#~#h
\$\endgroup\$
1
\$\begingroup\$

Klein, 21 + 3 bytes, (non-competing)

Uses the 000 topology.

:(1-(\))++@
1-+:?\)-(

Explanation

The first bit executed is :(1-(. This puts a copy of the input and a -1 in the scope to be recalled later. This is just required set up for future computation.

The two mirrors \\ then move the ip down a level into the main loop. The main loop, unfolded, is:

)-(1-+:?\

This recalls the first number of the scope and flips its sign then decrements the tos. It will continue to flip the sign back and forth until it reaches zero. This way it will be -1 if our input was even and 1 if it was odd. Once the counter has reached zero ? stops jumping over the mirror and the pointer wraps around to the top. Now the mirror we used earlier deflects the ip to the right causing it to run the code ))++@.

This code recalls the two things from the scope (the copy of the input and the number we have been flipping) with )). And adds the top three items with ++. Since the counter is at zero the result is just the sum of the number we built and the input. Since it can be either -1 or 1 depending on the parity of the input this will flip the sign of the input.

Finally @ ends execution.

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

braingasm, 8 bytes

;o[++]-:

; reads a number, o[++] increments twice if the number is odd, -decrements once, : prints.

edit: changed to p to o to retrofit to a breaking change in the language.

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

Casio-Basic, 27 bytes

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

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

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

Ly, 8 bytes

n:2%2*+,

Try it online!

Explanation:

n:2%2*+,

n        # take input
 :2%     # modulo two
    2*   # multiply by two
      +  # add to input
       , # decrement
\$\endgroup\$
1
\$\begingroup\$

tinylisp, 38 bytes

(load library
(q((N)((i(odd? N)a s)N 1

Try it online! (Adds 4 bytes to bind the lambda function to a name for ease of testing.)

Ungolfed

(load library)
(lambda (N)
  ((if (odd? N) add2 sub2) N 1))

Pretty straightforward implementation of the spec: if N is odd, add 1 to N; if not, subtract 1 from N. The main trick is that the if needs only swap out which function we're calling (addition vs. subtraction); the arguments (N and 1) are the same in either case.

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

MAWP, 18 bytes

%@!!2P2WA{M:}<1A:>

Try it!

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

Perl 5, 12 bytes

$_+=$_%2||-1

Try it online!

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

x86-16 machine code, 5 bytes

Binary:

00000000: 4834 0140 c3                             H4.@.

Listing:

48      DEC  AX             ; decrement input (parity now inverted)
34 01   XOR  AL, 1          ; if LSb is 0 (odd input) add 1, otherwise subtract 1
40      INC  AX             ; increment
C3      RET                 ; return to caller

Callable function, input/output is AL.

Explanation:

Classic XOR shenanigans to accomplish this equivalent if/else pseudocode:

AL = AL - 1
if ( AL & 1 == 0 ) AL = AL + 1
else AL = AL - 1
AL = AL + 1

Edit:

Well heck:

Silly me for not looking at existing submissions before starting. This approach was suggested by Ilmari Karonen in 2017!

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

Zsh, 14 bytes

<<<$[-(-$1^1)]

Try it online!

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

Python 3, 18 bytes

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

Try it online!

Explanation: Take the modulo of "n" and double it

Subtract that off the original "n" and subtract another 1

Basically, the same but easier to understand:

lambda n:n-(1-n%2*2)
\$\endgroup\$
1
\$\begingroup\$

Boolfuck, 91 57 56 bytes

,>,>,>,>,>,>,>+<<<<<<<+[>+]<[<]>+[>]+<[+<]>;>;>;>;>;>;>;

Try it online!

Yes, a real solution using Boolfuck.

Works on 7-bit integers, reads and writes in raw semibytes.

There might still be some optimization room here.

I mostly wanted to avenge my ,+; meme.

,>,>,>,>,>,>,       read 7 bits
>+<<<<<<<+[>+]<[<]> decrement
+                   xor 1
[>]+<[+<]           increment
>;>;>;>;>;>;>;      print
\$\endgroup\$
1
\$\begingroup\$

Python 3, 36 31 bytes

def f(n):return n+(-1)**(n%2+1)
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to Code Golf! You can save a ton by removing whitespace and using a lambda as well as modifying the algorithm a little: lambda n:abs((-1)**n-n). \$\endgroup\$
    – Makonede
    Apr 9, 2021 at 19:57
  • \$\begingroup\$ @Makonede Thanks for commenting, how do you remove whitespace? \$\endgroup\$ Apr 9, 2021 at 19:58
  • 2
    \$\begingroup\$ You just... don't use whitespace. That's literally it. You don't need to make a function on multiple lines: def f(n):return n+(-1)**(n%2+1) works \$\endgroup\$
    – Makonede
    Apr 9, 2021 at 19:59
0
\$\begingroup\$

C, 29 bytes

a(int b){return b%2?b+1:b-1;}
\$\endgroup\$
0
0
\$\begingroup\$

Jelly, 4 bytes

‘’Ḃ?

Try it online!

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

Batch, 20 bytes

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

Independently rediscovered @feersum's algorithm, honest!

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

CJam, 7 6 bytes

{(1^)}

Try it online!

-1 thanks to Martin Ender. ...............OOOO

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

C#, 34 11 bytes

n=>-(-n^1);

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

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

Swift, 29 bytes

var f={(i)->Int in i-1+i%2*2}

Try it here

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

Fourier, 17 bytes

I~x^ox%2{0}{@xvo}

Try it on FourIDE!

Explanation:

I~x                 - Stores input in a variable called x
   x^o              - Increments x and outputs
      x%2{0}{    }  - If x mod 2 == 0, do code inside brackets
             @      - Clear screen
              xvo   - Decrements x and outputs
\$\endgroup\$
0
\$\begingroup\$

05AB1E, 7 bytes

D1(sm-Ä

Try it online!

Explanation:

D1(sm-Ä
               Input (implicit). Is 3 for example. Stack: [3]
D              Duplicate input. Stack: [3, 3]
  1            Push 1. Stack: [3, 3, 1]
    (          Push opposite of top of stack. Stack: [3, 3, -1]
      s        Swap the top 2 items on the stack. Stack: [3, -1, 3]
        m      Push -1**3. Stack: [3, -1]
           -   Subtract. Stack: [4].
            Ä  Absolute value. Stack: [4].
               Implicit output.
\$\endgroup\$
0
\$\begingroup\$

Excel, 11 bytes

=A1-(-1)^A1

Assumes input in A1.

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

SAS, 72 bytes

%macro t(n);%put%eval(&n+%sysfunc(ifn(%sysfunc(mod(&n,2)),1,-1)));%mend;
\$\endgroup\$
0
\$\begingroup\$

dc, 10

?d2%2*+1-p

Uses the same formula as @TuukkaX's python answer.

Try it online.

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

Pyth, 4 bytes

I'm new to Pyth, so please tell me if there are any things I can golf.

_x1_

Explanation:

   _    Negate input
 x1     Bitwise XOR with 1
_       Negate
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Pyth! Hope you'll have a great time golfing in Pyth. \$\endgroup\$
    – Leaky Nun
    May 5, 2017 at 6:02
0
\$\begingroup\$

Excel VBA 27 bytes

[a2]=iif(n mod 2=0,n-1,n+1)
\$\endgroup\$
1
  • \$\begingroup\$ I don't think taking input from a variable is legal on PPCG (the question's worded a bit weirdly, but I don't think that permits it). You'd have to write a program or function. (Also, although it's optional, I recommend writing an explanation or brief description of how your code works; posts like this one which are just a code block have a tendency to set off the low-quality-posts filter, which can cause trouble sometimes.) \$\endgroup\$
    – user62131
    May 5, 2017 at 11:11
0
\$\begingroup\$

QBIC, 15 10 bytes

:?a-(-1)^a

Saved a lot by using a different calculation.

Explanation:

:           Get a number frm the cmd line as var a
?           PRINT
 a-(-1)^a   a decreased by 1 for when even, or -1 (adding one) when odd.

QBasic (and QBIC) need the parenteses around (-1), because code like -1^2 is otherwise seen as negate 1*1 = negate 1 = -1...

\$\endgroup\$

Your Answer

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

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