| Bytes | Lang | Time | Link |
|---|---|---|---|
| 050 | Setanta | 240809T015319Z | bb94 |
| 091 | Go | 240809T000359Z | bigyihsu |
| 050 | Common Lisp | 240808T222109Z | AlephSqu |
| 014 | Uiua | 240808T213054Z | nyxbird |
| 042 | R | 170624T085151Z | JAD |
| 059 | C gcc | 170502T152946Z | user5898 |
| 027 | Haskell | 170501T131809Z | nimi |
| 039 | C# | 170503T095934Z | user1655 |
| 037 | PHP | 170501T130948Z | Jör |
| 192 | x86 Assembler | 170509T214456Z | user6909 |
| 115 | C | 170509T214759Z | user6909 |
| 026 | Groovy | 170513T000642Z | David Co |
| 033 | Axiom | 170507T161657Z | user5898 |
| 075 | Java 7 | 170501T141857Z | Kevin Cr |
| 6362 | C | 170501T161510Z | Tim Čas |
| 027 | dc | 170502T162447Z | Digital |
| 035 | Pure Bash | 170502T161803Z | Digital |
| 020 | oK | 170502T141149Z | zgrep |
| 067 | Swift | 170501T215719Z | Caleb Kl |
| 026 | Ruby | 170502T070246Z | G B |
| 036 | PHP | 170502T064043Z | user6395 |
| 042 | C# | 170501T151912Z | MetaColo |
| 023 | TIBASIC | 170502T020354Z | Scott Mi |
| 029 | Cubix | 170501T235729Z | Luke |
| 024 | Dyvil | 170501T212900Z | Clashsof |
| 101 | vba | 170501T190822Z | SeanC |
| 008 | Pyth | 170501T162751Z | Erik the |
| 087 | Retina | 170501T155916Z | Neil |
| 135 | Batch | 170501T153405Z | Neil |
| 009 | Pyth | 170501T152654Z | isaacg |
| 025 | Mathematica 25 Bytes | 170501T140553Z | Kelly Lo |
| 050 | Vim | 170501T141443Z | xenia |
| 013 | Japt | 170501T135127Z | ETHprodu |
| 025 | Oasis | 170501T133915Z | Leaky Nu |
| 024 | JavaScript | 170501T133036Z | Business |
| 014 | J | 170501T132340Z | Leaky Nu |
| 010 | 05AB1E | 170501T131646Z | Adnan |
| 030 | Python | 170501T131549Z | user4594 |
| 012 | Pyth | 170501T130505Z | Leaky Nu |
| 012 | Actually | 170501T131312Z | user4594 |
| 008 | Jelly | 170501T130248Z | Leaky Nu |
| 012 | CJam | 170501T130301Z | Business |
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}
Port of @user1655772's answer.
Uiua, 14 bytes
⨬(-|+|×|ⁿ)◿4..
⨬(-|+|×|ⁿ)◿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
Haskell, 28 27 bytes
f x=cycle[0,x+x,x*x,x^x]!!x
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];
PHP, 47 Bytes
<?=(bc.[sub,add,mul,pow][($x=$argn)&3])($x,$x);
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.
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:
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
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
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.
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
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^
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
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*++
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.
Pyth, 12 bytes
.vjd,+@"-+*^
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, returnx-x(for consistency); - If
x%4==1, returnx+x; - If
x%4==2, returnx*x; - If
x%4==3, returnx^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 (too bad if you are in Turkey).
Actually, 12 bytes
;;3&"-+*ⁿ"Eƒ
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
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, returnx_x(subtraction) (for consistency); - If
x%4==1, returnx+x; - If
x%4==2, returnx×x(multiplication); - If
x%4==3, returnx*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.
CJam, 12 bytes
ri__"-+*#"=~
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