[Question]
  [
This is a CMC (chat mini challenge) that I posted in our chatroom, [The Ninteenth Byte](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte), a bit ago.
### The Challenge
Given a positive integer `x`, depending on the last 2 bits of `x`, do the following:
```
x & 3 == 0: 0
x & 3 == 1: x + x
x & 3 == 2: x * x
x & 3 == 3: x ^ x (exponentiation)
```
### Input/Output
```
Single Integer -> Single Integer  
```
A trailing newline is permitted in the output. No other whitespace is permitted.
### Testcases
```
input       output
    1            2
    2            4
    3           27
    4            0
    5           10
    6           36
    7       823543
    8            0
    9           18
   10          100
   11 285311670611
   12            0
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins!
  
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ị“+×*_”v
```
[Try it online!](https://tio.run/nexus/jelly#@/9wd/ejhjnah6drxT9qmFv239AoSOdwu8qjpjXu/wE "Jelly – TIO Nexus")
## How it works
Firstly, notice that `x&3` is equivalent to `x%4`, where `%` is modulo. Then, since Jelly uses modular indexing (`a[n] == a[n+len(a)]`), so we don't even need to deal with that.
Then:
* If `x%4==0`, return `x_x` (subtraction) (for consistency);
* If `x%4==1`, return `x+x`;
* If `x%4==2`, return `x×x`(multiplication);
* If `x%4==3`, return `x*x`(exponentiation)
Note that Jelly uses 1-indexing, so the subtraction `"_"` is moved to the end.
```
ị“+×*_”v  example input: 10
ị“+×*_”   index 10 of the string “+×*_”, which gives "×"
       v  evaluate the above as a Jelly expression,
          with 10 as the argument, meaning "10×" is the
          expression evaluated. The dyad "×" takes the
          second argument from the only argument, effectively
          performing the function to itself.
```
[Answer]
# [Python](https://docs.python.org/), 30 bytes
```
lambda x:[0,x+x,x*x,x**x][x%4]
```
[Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqhQYRVtoFOhXaFToQXCWhWx0RWqJrH/C4oy80o00jRAZGZeQWmJhiYQ/DcGAA "Python 3 – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 12 bytes
```
ri__"-+*#"=~
```
[Try it online!](https://tio.run/nexus/cjam#@1@UGR@vpKutpaxkW/f/vwUA "CJam – TIO Nexus")
### Explanation
```
ri            e# Read an int from input (call it x).
  __          e# Duplicate x twice.
    "-+*#"    e# Push this string.
          =   e# Get the character from the string at index x (mod 4).
           ~  e# Eval that char, using the two copies of x from before.
```
Runs one of the following operations depending on `x`'s value mod 4 (mod 4 is equivalent to AND 3).
```
0:  -  Subtraction
1:  +  Addition
2:  *  Multiplication
3:  #  Exponentiation
```
[Answer]
## Mathematica 25 Bytes
```
0[2#,#*#,#^#][[#~Mod~4]]&
```
Saved 4 Bytes thanks to @MartinEnder
[Answer]
# Pyth, 8 bytes
```
.v@"0y*^
```
[Interpreter](//pyth.herokuapp.com?code=.v%40%220y%2a%5E&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 26 bytes
```
->x{x*[0,2,x,x**~-x][x%4]}
```
[Try it online!](https://tio.run/nexus/ruby#S7P9r2tXUV2hFW2gY6RToVOhpVWnWxEbXaFqElv7X8NQT8/QSFMvN7GguqaipkAhLboCKAwA "Ruby – TIO Nexus")
[Answer]
# PHP, 37 Bytes
```
<?=[0,2*$x=$argn,$x*$x,$x**$x][$x&3];
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/992a252296d9bddff362ea213f918c004681c1dc)
# PHP, 47 Bytes
```
<?=(bc.[sub,add,mul,pow][($x=$argn)&3])($x,$x);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/29748e1a3da588d1988e55ed9d82273b2a6969e5)
[BC Math functions](http://php.net/manual/en/ref.bc.php)
[Answer]
## Haskell, ~~28~~ 27 bytes
```
f x=cycle[0,x+x,x*x,x^x]!!x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwja5MjknNdpAp0K7QqdCC4jjKmIVFSv@5yZm5inYKhQUZeaVKKgo5CYWKKQpRBvq6Rkaxf4HAA "Haskell – Try It Online")
Edit: Thanks to @Ørjan Johansen for 1 byte.
[Answer]
# JavaScript, 24 bytes
```
a=>[0,a+a,a*a,a**a][a%4]
```
[Try it online!](https://tio.run/nexus/javascript-node#S7P9n2hrF22gk6idqJOoBcJaibHRiaomsf@T8/OK83NS9XLy0zXSNCw0Na25UIUsMYUMDbCIGQLF/gMA "JavaScript (Node.js) – TIO Nexus")
[Answer]
# C, 63 or 62 bytes
```
#include<math.h>
f(x){return(int[]){0,x+x,x*x,pow(x,x)}[x&3];}
```
-1 byte if macros are allowed, assuming `x` is not an expression like `3+5` (since that'd mess up the precedence):
```
#include<math.h>
#define f(x)(int[]){0,x+x,x*x,pow(x,x)}[x&3]
```
[Answer]
# Java 7, 75 bytes
```
long c(int n){int x=n%4;return x<1?0:x<2?n+n:x<3?n*n:(long)Math.pow(n,n);}
```
Even though it is valid according to the rules, `long` is 64-bits, so it fails for the exponentiation test cases of `19^19` and above. To fix that we can use a `BigDecimal` approach:
**~~148~~ 146 bytes**
```
import java.math.*;BigDecimal c(int n){int x=n%4;BigDecimal m=new BigDecimal(n);return x<1?m.subtract(m):x<2?m.add(m):x<3?m.multiply(m):m.pow(n);}
```
**Explanation (of BigDecimal approach):**
```
import java.math.*;                // Import required for BigDecimal
BigDecimal c(int n){               // Method with integer parameter and BigDecimal return-type
  int x=n%4;                       //  Input modulo-4
  BigDecimal m=new BigDecimal(n);  //  Convert input integer to BigDecimal
  return x<1?                      //  If the input mod-4 is 0:
    m.subtract(m)                  //   Return input - input (shorter than BigDecimal.ZERO)
   :x<2?                           //  Else if the input mod-4 is 1:
    m.add(m)                       //   Return input + input
   :x<3?                           //  Else if the input mod-4 is 2:
    m.multiply(m)                  //   Return input * input
   :                               //  Else:
    m.pow(n);                      //   Return input ^ input
}                                  // End of method
```
**Test code:**
[Try it here.](https://tio.run/nexus/java-openjdk#TU9BasMwELz7FUOgINUgSNpeKptC6bWnHEsPiuwmKl5ZyKvEIfjtrpwU2sMyO7PDMOso9JHxbY5GkeGDuteF7cww4P1SAAMbdhbzq9u/tdaR6WCF8wwvLwuMtb971P@uVPv2hD9BeKljyyl6jNX6hdSQdhyNZUHyeaw2WTFNcyMPmVDq2IXuvCikQn9aAqYZCGnX5Sa/hY69a0DGebHl6Pz@4xNGLoWBrz7iWtGhxlpnqGpsnvJSlhI3D7A9D9yS6hOrkANY5LckSqw0VlJfTVOxzDT/AA)
```
import java.math.*;
class M{
  static BigDecimal c(int n){int x=n%4;BigDecimal m=new BigDecimal(n);return x<1?m.subtract(m):x<2?m.add(m):x<3?m.multiply(m):m.pow(n);}
  public static void main(String[] a){
    for (int i = 1; i <= 25; i++) {
      System.out.print(c(i) + "; ");
    }
  }
}
```
**Output:**
```
2; 4; 27; 0; 10; 36; 823543; 0; 18; 100; 285311670611; 0; 26; 196; 437893890380859375; 0; 34; 324; 1978419655660313589123979; 0; 42; 484; 20880467999847912034355032910567; 0; 50; 
```
[Answer]
## x86 Assembler, Intel syntax, 192 bytes
```
.data
f dw @q,@w,@e,@r
.code
mov ecx, eax
and ecx, 3
mov edx,dword ptr f[ecx*4]
call [edx]
ret
q:
xor eax,eax
ret
w:
add eax,eax
ret
e:
mul eax,eax
ret
r:
mov ecx,eax
t:
mul eax,eax
loop t
ret
```
Example pretends for fastest working speed. Is is a program or program part, which uses fastcall convention. It assumes input variable `x` in register `eax`, and returns result also in `eax`. Basic idea is stay away from using conditional jumps, as in some examples here. Also, it is not to evaluate everything (as in C example with arrays) but to use array of pointers to functons and make faster unconditional jumps (jmp/call) as an optimized "C language switch()-case.." analog. This technique could be also useful in kinds of finita automata - like processor emulators, executors and so on.
Upd: for x64 use "r" in register names, instead of "e" (e.g. `rax` instead of `eax`, `rcx` instead of `ecx`). Size will not be changed, and it will use 64-bit unsigned words.
[Answer]
# C#, 39 bytes
```
x=>new[]{0,2,x,Math.Pow(x,x-1)}[x&3]*x;
```
### Explanation
Observe that:
(x-x, x+x, x\*x, x^x) == (0, 2, x, x^(x-1)) \* x
The solution creates an array, indexes into it and then multiplies the result by `x`:
```
x => new[] { 0, 2, x, Math.Pow(x,x-1) }[x&3] * x;
```
### Alternative versions:
```
x=>new[]{0,x+x,x*x,Math.Pow(x,x)}[x%4];
```
(39B, all multiplication done in the array, `x%4` replaces `x&3`)
```
x=>x%4<2?x%2*2*x:Math.Pow(x,x%4<3?2:x);
```
(39B, same as @MetaColon's answer but `x%2*2*x` replacing `x*x%4<1?0:2`)
[Answer]
# [Actually](https://github.com/Mego/Seriously), 12 bytes
```
;;3&"-+*ⁿ"Eƒ
```
[Try it online!](https://tio.run/nexus/actually#@29tbaympKut9ahxv5LrsUn//xsDAA "Actually – TIO Nexus")
Explanation:
```
;;3&"-+*ⁿ"Eƒ
;;            two copies of input (so 3 total)
  3&          bitwise AND with 3
    "-+*ⁿ"E   index into this string
           ƒ  call the respective function
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
Ð"-+*m"è.V
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@394gpKutlau0uEVemH//5sCAA "05AB1E – TIO Nexus")
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
4&|{0,+:,*:,^~
```
[Try it online!](https://tio.run/nexus/j#@59ma2WiVlNtoKNtpaNlpRNX9z81OSNfIU3JQMHOyiFTT8HQqIIrtSKz5D8A "J – TIO Nexus")
[Answer]
# [Oasis](https://github.com/Adriandmen/Oasis), 25 bytes
```
mn4%3Q*nkn4%2Q*nxn4%1Q*++
```
[Try it online!](https://tio.run/nexus/oasis#@5@bZ6JqHKiVlw2kjYB0BZA2DNTS1v7//7@hIQA "Oasis – TIO Nexus")
## How it works
Notice that `x&3` is equivalent to `x%4`, where `%` is modulo.
```
mn4%3Q*nkn4%2Q*nxn4%1Q*++  input is n
mn4%3Q*                    (n**n)*((n%4)==3)
       nkn4%2Q*            (n**2)*((n%4)==2)
               nxn4%1Q*    (n*2)*((n%4)==1)
                       +   add the above two
                        +  add the above two
```
Oasis is a stack-based language where every character is a command.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 29 bytes
```
.;[[email protected]](/cdn-cgi/l/email-protection):4%!^s;((?u.^P;<^*;
```
[Try it online!](https://tio.run/nexus/cubix#@69nreev7aAX6u9pZaKqGFdsraFhX6oXF2BtE6dl/f@/OQA "Cubix – TIO Nexus")
Explanation will be added soon...
[Answer]
# C#, 42 Bytes
```
x=>x%4<2?x*x%4<1?0:2:Math.Pow(x,x%4<3?2:x)
```
Actually it's normal C#, but as you can't run it as a whole program and you have to type it into the interactive, I guess you may call it *C# interactive*.
**Explanation**:
```
x => (x % 4) < 2     //If the bits are smaller than 2 (1 or 0)
? x *           //multiply x with
    (x % 4) < 1 //if the bits are 0
    ? 0         //0 (results in 0)
    : 2         //or else with 2 (results in 2*x or x+x)
: Math.Pow(x,   //otherwise power x by
    (x % 4) < 3 //if the bits are 2
    ? 2         //2 (results in x^2 or x*x)
    : x);       //or else x (results in x^x)
```
I can't tell wether it's the shortest variant, any suggestions are appreciated.
[Answer]
# PHP, 36 bytes
```
<?=[0,2,$x=$argn,$x**~-$x][$x&3]*$x;
```
[Answer]
# dc, 27
I've never had the occasion to use arrays in dc before:
```
[+]1:r[*]2:r[^]3:r?dd4%;rxp
```
[Try it online](https://tio.run/nexus/bash#S8svUihJLS5JTixOVcjMU6g21NMzNKq1VkjJ51IAguLUEgVdXQUVmBqwYEFRZl5JmoK6arGCrp2COppsanJGPkJIoUYhJVlBN1VB6X@0dqyhVVG0VqwRkIyLNbYqsk9JMVG1Lqoo@K/ElZKfl/ofAA).
[Answer]
# Groovy, 26 bytes
```
{x->[0,x+x,x*x,x**x][x%4]}
```
[Try it online!](https://tio.run/nexus/groovy#q1CwVQiuLC5JzdXLzNPLSy0PSk1MSS3S0NQrAjJ8MvNSNTQVEosVMvNKuFJS0xTSFGz/V1fo2kUb6FRoV@hUaIGwVkVsdIWqSWzt/4IioMKcPI00jQpNzf/mAA "Groovy – TIO Nexus")
[Answer]
## C, 115 bytes
```
#include<math.h>
#define D(K,L)K(x){return L;}
D(q,0)D(w,x+x)D(e,x*x)D(r,pow(x,x))(*g[])()={q,w,e,r};D(f,g[x%4](x))
```
Example is a function `int f(int x)`
It pretends for fastest working speed as it keeps CPU away from using conditional jumps. And this is only correct speed-optimisation way for this task. Also, it tries not to evaluate everything, as in array C example `return(int[]){0,x+x,x*x,pow(x,x)}[x%4];` But but to wisely use array of pointers to functons, in order to make much faster unconditional jumps (jmp/call) with much faster address arithmetics, as an optimized version of "switch()-case..". This technique could be also useful in several kinds of finita automata - like processor emulators, executors, command stream parsers, and so on - where speed matters and code like `switch(x%4) case(0):... case(1):...` is unsuitable because it produces multiple cmp/jnz instructions; and these are [costly operations for CPU](https://en.wikipedia.org/wiki/Branch_predictor)
Simpliest and shortest test program (in default conditions) for the case will be as follows:
```
D(main,f(x))
```
It will add just 12 bytes of payload and will total our size to 127 bytes;
But you should better tell the linker to use `f` function as an entry point, instead of `main`. That is the way, if we aim to get fastest possible working binary for this task from shortest code ;-) This happens because C library adds extra init/shutdown code before calling your main() function.
Code compiles on MSVS Community 2015 without any tricks and issues and produces correct results. I haven't tested it with gcc, but i'm sure it will work fine as well.
[Answer]
# R, ~~47~~ 42 bytes
```
x=scan();c(`-`,`+`,`*`,`^`)[[x%%4+1]](x,x)
```
Applies the function `-`, `+`, `*`, or `^` based on the modulus of `x` to `x` and `x`.
`-` is the only (somewhat) smart thing, since `x-x` is always 0.
# R, 33 bytes
```
pryr::f(c(0,2*x,x^2,x^x)[x%%4+1])
```
Same method as other people use. Though it is shorter, I don't like it nearly as much.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
.vjd,+@"-+*^
```
[Try it online!](http://pyth.herokuapp.com/?code=.vjd%2C%2B%40%22-%2B%2a%5E&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12&debug=0)
## How it works
Firstly, notice that `x&3` is equivalent to `x%4`, where `%` is modulo. Then, since Pyth uses modular indexing (`a[n] == a[n+len(a)]`), so we don't even need to deal with that.
Then:
* If `x%4==0`, return `x-x` (for consistency);
* If `x%4==1`, return `x+x`;
* If `x%4==2`, return `x*x`;
* If `x%4==3`, return `x^x`.
---
```
.vjd,+@"-+*^  example input: 10
      @"-+*^  "-+*^"[10], which is "*"
     +        "*10"
    ,         ["*10","10"]
  jd          "*10 10"
.v            evaluate as Pyth expression
              (Pyth uses Polish notation)
```
More about Polish notation: [Wikipedia](https://en.wikipedia.org/wiki/Polish_notation) (too bad if you are in Turkey).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
Ov"^+*p"gU +U
```
[Try it online!](https://tio.run/nexus/japt#@@9fphSnrVWglB6qoB36/7@hIQA "Japt – TIO Nexus")
This uses the same method as the other eval answers, except the program `-U` just negates `U`, so we use `^` (bitwise XOR) instead.
[Answer]
## Vim, 50 bytes
```
y$o^R"A-+*^^V^[0^R"lx0"_Dp^[0D@"kJ0"ad$:r!echo ^R"^R0|bc^<Enter>
```
Here, `^V` represents a `Ctrl+V`, `^R` represents `Ctrl-R` and `^[` represents the `esc` key
Works by first building up the expression and then letting `bc` evaluate it. Expects the input on the first line in an otherwise empty buffer.
Explanation:
```
y$o^R"                                                          Copies the input into register " and pastes it on the second line
      A-+*^^V^[0^R"lx0"_Dp                                      Enters that text after the input on the second line
                          ^[0D@"                                Executes the second line as a Vim command.
                                                                For example, if the input is 12, the second line would be 12A-+*^^[012lx0"_Dp, which means:
                                                                  12A-+*^^[           Insert the text -+*^ 12 times
                                                                           012lx0"_Dp Go 12 chars to the right and remove everything except for that.
                                                                If effect, this basically just selects the appropriate operation.
                                kJ0"ad$                         Put the operator after the number, cut it into register a
                                       :r!                      Execute the following shell command and put the result into the buffer:
                                          echo ^R"^R0|bc<Enter> The shell command "echo [contents of register a][contents of registers 0]|bc. As said above, register a contains the input and the operator, and register 0 contains the input. The <enter> then executes this command.
```
[Answer]
# Pyth, 9 bytes
```
@[0yQ*QQ^
```
[Test suite](https://pyth.herokuapp.com/?code=%40%5B0yQ%2aQQ%5E&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12&debug=0)
Nothing fancy going on here, just calculate the four values, and select one with modular indexing.
```
@[0yQ*QQ^
@[0yQ*QQ^QQ)Q    Implicit variable introduction
@           Q    Modularly index into the following list
 [0        )     0
   yQ            Q*2
     *QQ         Q*Q
        ^QQ      Q^Q
```
[Answer]
## Batch, 135 bytes
```
@set/an=%1*2^&6
@goto %n%
:6
@set n=1
@for /l %%i in (1,1,%1)do @set/an*=%1
@goto 0
:4
@set n=%1
:2
@set/an*=%1
:0
@echo %n%
```
I was hoping to create the exponentiation by building up and evaluating a string of the form `[0+...+0, 2+...+2, x+...+x, x*...*x]` depending on the last two bits of `x` but unfortunately the code to select the operation took too long to express because I couldn't use `*` as a `for` parameter, but I was at least able to use some fall-though trickery to golf away some bytes.
[Answer]
# [Retina](https://github.com/m-ender/retina), 87 bytes
```
.+
$*1;$&$*
;((1111)*)(1?)$
;$3$3
1(?=1.*;((1111)*111)$)
$1;
+`\G1(?=.*;(1*))|;1*$
$1
1
```
[Try it online!](https://tio.run/nexus/retina#PckxEkBAEETRvM/R1MyoUtoimVJClxA4iLsvm/jBT15n513HAQwlewbSTF8ebjqcSBYWyI5dY/zYRgeVGO7rbNxU4f6kgp9AtU4QZhQsWLG9 "Retina – TIO Nexus") (Link includes test suite.)
Explanation: The first two lines convert the input into unary and duplicate it (so we now have `x;x`). The next two lines look for an `x&3` of either `0` or `1` and change `x;x` into `x;0` or `x;2` appropriately. The next two lines look for `x&3==3` and change `x;x` into `x;x;x;...;x;1;x` (`x` `x`s). This means that we have either `x;0`, `x;2`, `x;x`, or `x;...;x` and it remains to multiply everything together and convert back to decimal. (The multiplication code is based on that in the Retina wiki but amended to handle multiplication by zero.)
]