g | x | w | all
Bytes Lang Time Link
050Setanta240809T015319Zbb94
091Go240809T000359Zbigyihsu
050Common Lisp240808T222109ZAlephSqu
014Uiua240808T213054Znyxbird
042R170624T085151ZJAD
059C gcc170502T152946Zuser5898
027Haskell170501T131809Znimi
039C#170503T095934Zuser1655
037PHP170501T130948ZJör
192x86 Assembler170509T214456Zuser6909
115C170509T214759Zuser6909
026Groovy170513T000642ZDavid Co
033Axiom170507T161657Zuser5898
075Java 7170501T141857ZKevin Cr
6362C170501T161510ZTim Čas
027dc170502T162447ZDigital
035Pure Bash170502T161803ZDigital
020oK170502T141149Zzgrep
067Swift170501T215719ZCaleb Kl
026Ruby170502T070246ZG B
036PHP170502T064043Zuser6395
042C#170501T151912ZMetaColo
023TIBASIC170502T020354ZScott Mi
029Cubix170501T235729ZLuke
024Dyvil170501T212900ZClashsof
101vba170501T190822ZSeanC
008Pyth170501T162751ZErik the
087Retina170501T155916ZNeil
135Batch170501T153405ZNeil
009Pyth170501T152654Zisaacg
025Mathematica 25 Bytes170501T140553ZKelly Lo
050Vim170501T141443Zxenia
013Japt170501T135127ZETHprodu
025Oasis170501T133915ZLeaky Nu
024JavaScript170501T133036ZBusiness
014J170501T132340ZLeaky Nu
01005AB1E170501T131646ZAdnan
030Python170501T131549Zuser4594
012Pyth170501T130505ZLeaky Nu
012Actually170501T131312Zuser4594
008Jelly170501T130248ZLeaky Nu
012CJam170501T130301ZBusiness

Setanta, 50 bytes

gniomh(x){toradh[0,x+x,x*x,cmhcht@mata(x,x)][x%4]}

try-setanta.ie link

Go, 91 bytes

import."math"
func f(x int)int{return[]int{0,2,x,int(Pow(float64(x),float64(x-1)))}[x&3]*x}

Attempt This Online!

Port of @user1655772's answer.

Common Lisp, 50 bytes

(lambda(x)(apply(elt'(- + * expt)(mod x 4))x x()))

Try it online!

Uiua, 14 bytes

⨬(-|+|×|ⁿ)◿4..

Try it!

⨬(-|+|×|ⁿ)◿4..
⨬              # switch on
          ◿4.  # the input modulo 4
 (-|+|×|ⁿ)     # and call -, +, *, or ^ on
             . # the input duplicated

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.

C (gcc), 59 bytes

#include<math.h>
h(x){return x&2?pow(x,x&1?x:2):(x&1)*2*x;}

Test and results. It overflows at 11.

main()
{int i;
 for(i=0;i<20;++i)
       printf("%u %u\n", i, h(i));
}

0 0
1 2
2 4
3 27
4 0
5 10
6 36
7 823543
8 0
9 18
10 100
11 1843829075
12 0
13 26
14 196
15 1500973039
16 0
17 34
18 324
19 0

Ideone

Try it online!

Haskell, 28 27 bytes

f x=cycle[0,x+x,x*x,x^x]!!x

Try it online!

Edit: Thanks to @Ørjan Johansen for 1 byte.

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)

PHP, 37 Bytes

<?=[0,2*$x=$argn,$x*$x,$x**$x][$x&3];

Online Version

PHP, 47 Bytes

<?=(bc.[sub,add,mul,pow][($x=$argn)&3])($x,$x);

Online Version

BC Math functions

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.

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

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.

Groovy, 26 bytes

{x->[0,x+x,x*x,x**x][x%4]}

Try it online!

Axiom, 59 33 bytes

h(x)==[0,x+x,x*x,x^x].(1+x rem 4)

traslate in Axiom the answer of Mego... this is the old 59 bytes

h(x)==(x quo 2 rem 2=1=>(x rem 2=0=>x^2;x^x);(x rem 2)*2*x)

results

(24) -> for i in 0..30 repeat output [i,h(i)]
   [0,0]
   [1,2]
   [2,4]
   [3,27]
   [4,0]
   [5,10]
   [6,36]
   [7,823543]
   [8,0]
   [9,18]
   [10,100]
   [11,285311670611]
   [12,0]
   [13,26]
   [14,196]
   [15,437893890380859375]
   [16,0]
   [17,34]
   [18,324]
   [19,1978419655660313589123979]
   [20,0]
   [21,42]
   [22,484]
   [23,20880467999847912034355032910567]
   [24,0]
   [25,50]
   [26,676]
   [27,443426488243037769948249630619149892803]
   [28,0]

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.

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; 

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]

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.

Pure Bash, 35

a=(- + * **)
echo $[$1${a[$1%4]}$1]

Try it online.

oK, 20 bytes

{*/(."-+*#"4!x).x,x}

Try it online!

Swift, 105 68 67 bytes

Here is the body of the function:

i in let a=i%4;return [0,i+i,i*i,Int(pow(Double(i),Double(i)))][a]

Here is the full implementation:

import Foundation;var e:(Int)->Int={i in let a=i%4;return [0,i+i,i*i,Int(pow(Double(i),Double(i)))][a]}

Try it here

Ruby, 26 bytes

->x{x*[0,2,x,x**~-x][x%4]}

Try it online!

PHP, 36 bytes

<?=[0,2,$x=$argn,$x**~-$x][$x&3]*$x;

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.

TI-BASIC, 27, 23 bytes

:Prompt X          //Get input as X, 3 bytes
:{2X,X²,X^X,0      //Implicitly store the list {2X,X²,X^X,0} to Ans, 16 bytes
:Ans(remainder(X,4 //Compute X&3 (as X%4), get that element of the list, and implicitly print 8 bytes

TI-BASIC doesn't have bitwise operators, so I used the modulus operator (remainder() instead.

Cubix, 29 bytes

.;.O+@.UOI:4%!^s;((?u.^P;<^*;

Try it online!

Explanation will be added soon...

Dyvil, 24 Bytes

x=>[0,x+x,x*x,x**x][x&3]

Usage:

let f: int->int = x=>[0,x+x,x*x,x**x][x&3]
print f(10) // => 100

Explanation:

The code creates a lambda expression that takes and returns a 32-bit integer. The body stores the result of all calculations in an array and retrieves the result from the index given by the last 2 bits of x.

vba, 101

Function x(f)
Select Case f Mod 4
Case 0:x=0
Case 1:x=f+f
Case 2:x=f*f
Case 3:x=f ^f
End Select
End Function

Pyth, 8 bytes

.v@"0y*^

Interpreter

Retina, 87 bytes

.+
$*1;$&$*
;((1111)*)(1?)$
;$3$3
1(?=1.*;((1111)*111)$)
$1;
+`\G1(?=.*;(1*))|;1*$
$1
1

Try it online! (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 xs). 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.)

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.

Pyth, 9 bytes

@[0yQ*QQ^

Test suite

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

Mathematica 25 Bytes

0[2#,#*#,#^#][[#~Mod~4]]&

Saved 4 Bytes thanks to @MartinEnder

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.

Japt, 13 bytes

Ov"^+*p"gU +U

Try it online!

This uses the same method as the other eval answers, except the program -U just negates U, so we use ^ (bitwise XOR) instead.

Oasis, 25 bytes

mn4%3Q*nkn4%2Q*nxn4%1Q*++

Try it online!

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.

JavaScript, 24 bytes

a=>[0,a+a,a*a,a**a][a%4]

Try it online!

J, 14 bytes

4&|{0,+:,*:,^~

Try it online!

05AB1E, 10 bytes

Ð"-+*m"è.V

Uses the 05AB1E encoding. Try it online!

Python, 30 bytes

lambda x:[0,x+x,x*x,x**x][x%4]

Try it online!

Pyth, 12 bytes

.vjd,+@"-+*^

Try it online!

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:


.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 (too bad if you are in Turkey).

Actually, 12 bytes

;;3&"-+*ⁿ"Eƒ

Try it online!

Explanation:

;;3&"-+*ⁿ"Eƒ
;;            two copies of input (so 3 total)
  3&          bitwise AND with 3
    "-+*ⁿ"E   index into this string
           ƒ  call the respective function

Jelly, 8 bytes

ị“+×*_”v

Try it online!

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:

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.

CJam, 12 bytes

ri__"-+*#"=~

Try it online!

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