g | x | w | all
Bytes Lang Time Link
nanC++ gcc250818T115316ZToby Spe
223Bespoke250818T102513ZJosiah W
nanUiua250327T105639ZjanMakos
nanJanet250327T092843ZAdam
034AWK250326T175707Zxrs
041Tcl190418T134926Zsergiol
1459Pari/GP170713T130613Zalephalp
058C# 635 =141123T231402Zbinderbo
057Go230626T220111Zbigyihsu
nanLua230626T022736Zbluswimm
510505AB1E190418T120632ZKevin Cr
1055Thunno 2230625T170206ZThe Thon
038Branch210418T010100Zhyperneu
033Rust210407T204855ZUndersla
nanVyxal201031T000510Zlyxal
1156Husk201030T153121ZDominic
954Stax210407T070617ZRazetime
nanHusk201030T165922ZDominic
7158Scala200904T134458Zuser
nanR201030T150351ZDominic
nanGoogle Sheets200904T155708ZGeneral
1358Arn200904T141429ZZippyMag
nanKeg191116T042540Zlyxal
nanC gcc191115T191813Zceilingc
nanPowerShell190812T195505ZVeskah
030C gcc190419T064940Zceilingc
nanPerl 6190419T035516Zbb94
nanR190418T174930ZSumner18
030Zsh190418T175934ZGammaFun
nanForth gforth190418T152509Zreffu
01205AB1E190418T134933ZMagic Oc
027Swift190418T133826Zielyaman
027Haskell171220T182213Ztotallyh
nanJelly170713T130900ZErik the
039Java OpenJDK 8170713T125552ZXanderha
8157APL Dyalog170713T123916ZAdá
002Ruby150305T173014Zblutoran
nanPARI/GP160323T163609ZCharles
061C160323T145730ZCole Cam
nanRuby151204T062353ZDanieth
nan141121T221205ZFryAmThe
047OCaml141210T223604Zusernumb
043Marbelous141121T230954ZMartin E
117C 105141122T194804Zbacchusb
nanHaskell GHCi141125T050719ZRentsy
031Python141124T210557Zkukac67
077C141122T232929ZRames
nanMATLAB141122T145659ZStewie G
072Java 8 Score141122T210149ZTheNumbe
nan141124T100239ZRodolfo
022Groovy 275 =141124T122053ZArmand
031Clojure141122T231038ZBob Jarv
034Emacs Lisp –141124T011925ZSean All
020TIBASIC NSpire 5141121T171215ZShujal
1257CJam141121T154805ZMartin E
nanBefunge98141121T220123ZKasran
028Python141121T172829ZDigital
024JavaScript ES6 295 =141121T160559ZMichael
nanPerl141121T215648Zhobbs
nanHaskell141121T202905Zcolevk
nan141121T192047ZMegaTom
nanPure bash141121T190022ZDigital

C++ (gcc), 54 bytes - 15 bonus = 39 points

#include<complex>
#define f(x)std::polar(1.,x*acos(0))

GCC seems to transitively include <math.h> when we ask for <complex>.

Try it online!

Bespoke, 223 bytes, score 218 (-5)

find I,power N
in fact,this is actually noncomplex;they do periodic cycles
squared is-one;it goes every fourth in pattern,too
then-Is,negating itself
finally is one
and a repetition comes around at an I
repeats for always:I

Outputs - if (n // 2) % 2 is nonzero; outputs i if n % 2 is nonzero; outputs 1 at end (which I've set up to error out with a stack underflow error if i was outputted).

Uiua, 5 - 15 = -10 bytes

I think this is the first solution with a negative byte count.

ℂ°∠×η

Test cases

Explanation

ℂ°∠×η

   ×η # Multiply by eta (pi/2 constant) 
 °∠   # Get the sine and cosine
ℂ     # Make a complex number

Janet, 24 - 5 = 19 bytes

|([1"i"-1"-i"](mod $ 4))

AWK, 34 bytes

{split("1 i -1 -i",x)}$0=x[$1%4+1]

Attempt This Online!

{split("1 i -1 -i",x)} # create array
$0=                    # set output
x[$1%4+1]              # AWK is 1 indexed

Tcl, 41 bytes

proc I n {lindex {1 i -1 -i} [expr $n%4]}

Try it online!

Pari/GP, 14 bytes - 5 = 9

As a ring, \$\mathbb{C}\$ is isomorphic to \$\mathbb{R}[x]/(x^2+1)\$.

n->i^n%(i^2+1)

The i here is just a symbol, not the imaginary unit (which is I in Pari/GP).

Try it online!

C# 63-5 = 58

public string m(int n)=>n%2==0?(n%4==0?"1":"-1"):(m(n-1)+"i");

Go, 75 57 bytes, no bonus

func(n int)string{return[]string{"1","i","-1","-i"}[n%4]}

Try it online!

if n<0{n=4+n} is included here because the % operator in Go returns negative if the dividend is negative.

Lua, 33 - 5 = 28 bytes

print(({1,'i',-1,'-i'})[...%4+1])

Try it online!

05AB1E, score 5 (10 bytes - 5 bonus)

1'i®„-i)Iè

Try it online or verify some more test cases.

Explanation:

1           # Push 1
 'i        '# Push character "i"
   ®        # Push -1
    „-i     # Push string "-i"
       )    # Wrap everything on the stack into a list: [1,"i",-1,"-i"]
        Iè  # Use the input to (modular 0-based) index into it
            # (and output the result implicitly)

Thunno 2, 10 - 5 = 5 bytes

`-iu'i1K$i

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

Explanation

`-iu'i1K$i  '# Implicit input
`-i          # Push the string "-i"
   u         # Push the number -1
    'i      '# Push the string "i"
      1      # Push the number 1
       K     # Wrap the stack into a list
             # -> [1, "i", -1, "-i"]
        $i   # Index the input in
             # (0-based, modular)
             # Implicit output

Branch, 38 bytes

^\4^%/;c1^>/0c45^?[.0]anc2^%/49c105^?.

Try it on the online Branch interpreter!

Explanation

      Implicit - the initial node's value is set to the first argument
^\4   Create a parent and sibling and set the right child to 4
%     Modulo
/;    Go to the left child and copy the mod result
c1    Go to the right child (automatically assigned register C) and set it to 1
^     Return to the parent (the mod result)
>     1 if the mod result is greater than 1, 0 otherwise
/0    Go to the left child and set to 0
c45   Go to the right child and set it to 45 (codepoint for "-")
^     Return to the parent
?     Conditional - if the mod was greater, go to the right child (45), and left child (0) otherwise
[  ]  While the value isn't 0
 .    Output it
  0   And set it to zero (this is basically an if statement)
an    Go to the left child and load the first argument (register N by default)
c2    Go to the right child and set it to 2
%     Modulo
/49   Go to the left child and set it to 49 (codepoint for "1")
c105  Go to the right child and set it to 105 (codepoint for "i")
^     Go to the parent
?     Conditional - if the exponent was even, go left, otherwise, go right
.     Output

Rust 34 33 bytes

fn main() {
	// closure:
	// |n:usize|["1","i","-1","-i"][n%4]
	
	// call with: 
	print!("{}", (|n:usize|["1","i","-1","-i"][n%4])(3));	
}

Try it online!

The closure itself:

|n:usize|["1","i","-1","-i"][n%4]

Vyxal, r, 5 - 15 = -10 bytes

90*1"

Try it Online!

Well if the Ruby answer's output method is valid, so is this. Outputs in "polar form (angular unit: degrees)".

Explained

90*1"
90*   # Multiply the input by 90
   1" # Push one and pair the two inputs. The `-r` flag makes dyads take their arguments in reverse.

Husk, (14 11 bytes - 5) = 6

Edit: -3 bytes thanks to Razetime

!C2¨¹-1-i 1

Try it online!

Stax, 9 - 5 = 4 bytes

ü▲τ}εT├?á

Run and debug it

Husk, (30 bytes - 15) = 15

m₁m*1.57Ṡe-1
Σz*İ_m§/Π`^⁰↑99İ1

Try it online!

(The header in TIO rounds the rational number output into a fraction with maximum 3-digit numerator & demominator, for readability)

Calculations with real numbers are a bit ticky in Husk, since it doesn't have any trigonometric functions. So here I implement -sin(x) as Σz*İ_m§/Π`^⁰↑99İ1 (99 iterations of the Taylor series), and use 1.57 as a very rough approximation for pi/2.

To make matters even more difficult, Husk natively outputs rational numbers as fractions, rather than decimals. So there aren't any 'floating point' inaccuracies (but there are, of course, inaccuracies!). The byte-count to round-away the (non-floating-point) inaccuracies for integer inputs is currently not included in the score. Add +10 bytes to include it.

Scala, 7 bytes - 15 = -8

Port of @blutorange's devious Ruby answer. Go upvote that!

1->_*90

Try it online!

Takes a BigDecimal as input, outputs (Int,BigDecimal), but honestly, you could make it work for any type with a * method.

Crazier solution, 3 bytes - 15 = -12

90*

Try it online!

First component is assumed to be 1, so it only returns the second.

Boring solution, 30 27 bytes

" 1 i-1-i"drop _%4*2 take 2

Try it online!

R, (29 bytes -15) = 14

cos(m<-scan()*pi/2)+sin(m)*1i

Try it online!

Conventional complex number output; works for negative and real inputs.

(for completeness, there is also c(1,scan()*90) for a score of -1, using blutorange's dubious inventive polar output format in degrees)

Google Sheets, 32-15=17

Arn, 13 bytes - 5 = 8

◄š<f5®…┘┤ï\α

Try it!

Explained

Unpacked: [1"i"n_1"-i"]?%4

  [        Begin sequence
    1      Literal one
    "i"    String
    n_     Negate
      1
    "-i"
  ]        End sequence
?          Indexed by
    _      Variable initialized to STDIN; implied
  %        Modulo
    4      Literal four

Keg, 15 - 5 = 10 bytes

1i0;`-i`¿4%⊙&ø&

Try it online!

Pushes the four different possibilities and then takes the input modulo 4 and indexes the stack.

C (gcc), 44 bytes -15=29

#define f(x)cos(x*acos(0))+1i*sin(x*acos(0))

Try it online!

Handles signed and noninteger arguments.

PowerShell, 28 bytes -5 = 23

('i',-1,'-i',1)["$args"%4-1]

Try it online!

Port of all the cyclic indexing

C (gcc), 30 bytes

f(x){printf(L"iㄭ椭1"+x%4);}

Try it online!

Perl 6, 19 bytes - 5 = 14

{<1 i -1 -i>[$_%4]}

The result of % has the same sign as the divisor in this language.

Try it online!

R, 29 - 5 = 24 bytes

c(1,"i",-1,"-i")[scan()%%4+1]

Try it online!

Same as most methods above, takes a modulo of 4, and increases that by 1, because R's arrays are 1-indexed. Works for negative integers as well.

I was worried about mixed outputs here, but Giuseppe pointed out that R coerces numeric types to string types when they are mixed.

Zsh, 30 bytes, score 25 (-5)

a=({,}{,-}{1,i})
<<<$a[$1%4+5]

Try it online!

Based on the bash answer, but with some changes needed:

Forth (gforth), 53 bytes - 5 bytes (bonus) = 48 bytes

: f 4 mod dup 1 > if ." -"then 2 mod 56 * '1 + emit ;

Try it online!

This works for both positive and negative numbers

Code Explanation

: f             \ start a new word definition
  4 mod dup     \ get result of n % 4 (and make a copy)
  1 > if        \ if result is 2 or 3
    ." -'       \ print a minus sign
  then          \ end the if
  2 mod 56 *    \ get result modulo 2 and multiply by 56 (difference between ascii for '1' and 'i')
  '1 +          \ add to ascii value of '1'
  emit          \ output the character for the given value
;               \ end the word definition

05AB1E, 12 bytes

®sfgm¹Éi1'i:

Try it online!


®             # Push -1 onto the stack.
 sfg          # Push the number of prime factors of input.
    m         # -1^(number_prime_factors)
     ¹Éi      # is input even?
        1'i:  # if input was even, replace 1 with i.

Swift, 27

{["1","i","-1","-i"][$0%4]}

Try it online

Haskell, 27 bytes

(cycle(words"1 i -1 -i")!!)

Try it online!

Jelly, 2 - 20 = -18 bytes

ı*

Try it online!

It doesn't use an i ^ x builtin but it uses builtins for 1j and ** so not sure if allowed.

Java (OpenJDK 8), 39 bytes

n->new String[]{"1","i","-1","-i"}[n%4]

Try it online!

APL (Dyalog), 8 chars - 15 bonus = score -7

The built-in (and thus prohibited) function is 0J1*⊢, but this uses @blutorange's method.

¯12○.5×○

The challenge author, Kezz101, wrote:

If you support any real number you can output in any valid complex form.

This returns a complex number in the form aJb which is the normal way for APL to display complex numbers.

Try it online!

Explanation

¯12○ find the unit vector which has the angle in radians of

.5× one half times

 the argument multiplied by 𝜋 (the circle constant)

Ruby, score -2

(13 bytes, -15 bonus)

->n{[1,90*n]}

Features include: no rounding errors! (if you pass the input as a Rational)


posted by the author, Kezz101

If you support any real number you can output in any valid complex form.

Negatives scores make my adrenaline rush forth. Thus the rules get abused are made use of to achieve this noble goal.

Creates an anonymous function and outputs an array with 2 entries representing a complex number in polar form (angular unit: degrees).

PARI/GP, 26 - 5 = 21

n->Str([1,I,-1,-I][n%4+1])

n->cos(t=Pi*n/2)+I*sin(t) is one character shorter, but doesn't handle exact answers. Of course n->I^n is disallowed, and presumably also PARI's powIs.

C, 61

main(n){scanf("%d",&n);printf("%c%c",n%4/2*45,n%4%2?'i':49);}

Try it here.

Ruby, 208 - 15 = 193

p=Math::PI/2;t=gets.to_f*p;l=->n{Math::cos(n).round(2)};k=l.call(t);if k!=0;k=k.to_i if k.abs==1;print k;end;m=l.call(t+p);if m!=0;r="i";r='-'+r if m==-1;r="#{m}"+r if 1>m && -1<m;r=" + "+r if k!=0;puts r end

This implementation completely conforms to the spec! 1.0 is written as 1, -1.0i is written as -i, etc. I don't see any other solution that incorporates this along with supporting floating points, except for maybe the TI-Calculator.

Ungolfed:

p=Math::PI/2
t=gets.to_f*p
l=->n{Math::cos(n).round(2)}

k=l.call(t)
if k!=0
  k=k.to_i if k.abs==1
  print k
end

m=l.call(t+p)
if m!=0
  r="i"
  r='-'+r if m==-1
  r="#{m}"+r if 1>m && -1<m
  r=" + "+r if k!=0
  puts r
end

Python 2 - (24-5)=19

lambda n:'1i--'[n%4::-2]

Most credit belongs to @user2357112, I just golfed his answer from the comments on this answer a bit more.

Explanation: Starts at the index n%4 in the string '1i--'. Then iterates backwards in steps of two over each letter in the string. So, for example, n=6 would start at index 2, the first -, then skip the i and take the 1, to return -1.

@xnor pointed out a same-length solution:

lambda n:'--i1'[~n%4::2] 

Pyth - (14-5)=9

I can only seem to get 14, no matter how I try to reverse/slice/etc. :'(

%_2<"1i--"h%Q4

Which is essentially the same as the above python answer, but in 2 steps, because pyth doesn't support the full indexing options of python. Try it online.

I'm going to go have a talk with isaacg about Pyth indexing ;)

OCaml 47

let m n=List.nth["1";"i";"-1";"-i"](n mod 4);;

Not an award winning solution, but this is my first time code-golfing, so I'm not exactly sure of what I'm doing. I tried to use pattern matching, but that got me over 58.

Marbelous, 43 bytes

Not really a winner, but Marbelous is fun. :)

}0
^0
=0&2
&1
}0
^1\/
=0&02D3169
\/\/&0&1&2

This is a program which reads the input as a single integer from the first command-line argument. Note that the input is taken modulo 256, but this doesn't affect validity of the result for inputs greater than 255, because 256 is divisible by 4.

Explanation

Marbelous is a 2D programming language, which simulates "marbles" (byte values) falling through a bunch of devices. The board is made up of 2-character wide cells (the devices), which can process the marbles. Everything that falls off the bottom of a board is printed to STDOUT.

Let's go through the devices in use:

So in effect, what I do is to hold the three relevant characters in three synchronisers, and release those depending on how the least significant bits are set in the input.

For more information, see the spec draft.

C 105, was 117

char c[2];
int main()
{
int n,i,j=0;scanf("%d",&n);i=n%4;
i>1?c[j++]='-':c[j+1]='\0';
c[j]=i&1?'i':'1';
puts(c);
}

Haskell GHCi, 29 Bytes - 15 = 14

i p=[cos(p*pi/2),sin(p*pi/2)]

Usage:

*Main> i 0
[1.0,0.0]
*Main> i pi
[0.22058404074969779,-0.9753679720836315]
*Main> i (-6.4)
[-0.8090169943749477,0.5877852522924728]

Python - 31

print[1,'i',-1,'-i'][input()%4]

I have only recently started learning python. Even though I know it's not good, it's the best I can do.

C 77

main(){int n;scanf("%d",&n);char c[]={n%4>1?'-':' ',~n%2?'1':'i',0};puts(c);}

Improved thanks to Ruslan

C 74-5=69

Oh and of course the most obvious approach

main(){unsigned n,*c[]={"1","i","-1","-i"};scanf("%d",&n);puts(c[n%4]);}

MATLAB, 33 bytes - 5 = 28

x={'i','-1','-i','1'};x(mod(n,4))

Even though it's a few bytes more (37-5=32), I actually like this approach better:

x='1i -';x((mod([n/2,n],2)>=1)+[3,1])

Java 8 Score: 72

In Java, the worst golfing language ever! Golfed:

java.util.function.Function s=n->{new String[]{"i","-1","-i","1"}[n%4]};

Expanded:

class Complex{

    java.util.function.Function s = n -> {new String[]{"i","-1","-i","1"}[n%4]};

}

Note: I'm not used to Java 8. I also do not have the runtime for it yet. Please tell me if there are any syntax errors. This is also my first golf.

Edit: Removed import.

Edit: Removed class declaration.

Another answer with score = 87 - 15 = 72

java.util.function.Function s=n->{Math.cos(n*Math.PI/2)+"+"+Math.sin(n*Math.PI/2)+"i"};

Expanded:

class Complex{

    java.util.function.Function s = n -> {Math.cos(n * Math.PI/2) + " + " + Math.sin(n * Math.PI/2) + "i"};

}

Java: 151 131-5=126

Golfed:

class A{public static void main(String[]a){int n=Integer.parseInt(a[0]);System.out.print(n%4==0?"1":n%4==1?"i":n%4==2?"-1":"-i");}}

Ungolfed:

class A {
    public static void main(String[] a) {
        int n = Integer.parseInt(a[0]);
        System.out.print(n % 4 == 0 ? "1" : n % 4 == 1 ? "i" : n % 4 == 2 ? "-1" : "-i");
    }
}

As a function: 72-5=67

Golfed:

void f(int n){System.out.print(n%4==0?"1":n%4==1?"i":n%4==2?"-1":"-i");}

Ungolfed:

public void f(int n) {
    System.out.print(n % 4 == 0 ? "1" : n % 4 == 1 ? "i" : n % 4 == 2 ? "-1" : "-i");
}

Yes, yet another Java reply - and golfed even worse than ever. But you work with what you can...

EDIT: added function version.

EDIT 2: so, after a bit of trial and error, here's a version that tries to do it by the book, without exploring the cycle loophole. So…

Java with value calculation: 146-15=131

Golfed:

class B{public static void main(String[]a){float n=Float.parseFloat(a[0]);System.out.print(Math.cos((n*Math.PI)/2)+Math.sin((n*Math.PI)/2)+"i");}}

Ungolfed:

class B {
    public static void main(String[] a) {
        float n = Float.parseFloat(a[0]);
        System.out.print(Math.cos((n * Math.PI) / 2) + Math.sin((n * Math.PI) / 2) + "i");
    }
}

(at least, I think I can claim the top bonus, correct me otherwise)

Groovy: 27-5 = 22

f={n->[1,'i',-1,'-i'][n%4]}

Clojure (64 54 31 chars)

(defn i2n[n](println(case(mod n 4) 1 "i" 2 "-1" 3 "-i" 0 "1")))

Edit

Per @SeanAllred's suggestion, here's a version which uses a literal vector instead of a case function:

(defn i2n[n](println (["1" "i" "-1" "-i"] (mod n 4))))

Edit 2

By counting on the REPL to print out the resultant collection and coding the function using the #() shortcut we can reduce it to

#(["1" "i" "-1" "-i"](mod % 4))

(Which is actually much more Clojure/Lisp-ish as the function now actually returns the generated result, allowing the function to be used with map, as in

(map #(["1" "i" "-1" "-i"](mod % 4)) [0 1 2 3 4 5 6 7 8])

which prints

("1" "i" "-1" "-i" "1" "i" "-1" "-i" "1")

Share and enjoy.

(Emacs) Lisp – 34

Just for fun, in (Emacs) Lisp:

(lambda(n)(elt[1 i -1 -i](% n 4)))

If you want to use it, use a defun or use funcall:

(funcall
 (lambda (n) (elt [1 i -1 -i] (% n 4)))
 4) => 1

(mapcar
 (lambda(n)(elt[1 i -1 -i](% n 4)))
 [0 1 2 3 4 5 6 7 8])
 => (1 i -1 -i 1 i -1 -i 1)

TI-BASIC (NSpire) - 5 (20 characters-15)

cos(nπ/2)+sin(nπ/2)i

If you want to recieve a complex return value, replace the i at the end with (complex i).

CJam, 12 characters - 5 = 7

1'iW"-i"]li=

Test it here.

Supports negative inputs.

1              "Push 1.";
 'i            "Push the character i.";
   W           "Push -1.";
    "-i"       "Push the string -i.";
        ]      "Wrap all four in an array.";
         li    "Read STDIN and convert to integer.";
           =   "Access array. The index is automatically taken module the array length.";

The result is printed automatically at the end of the program.

Mathematica, 22 20 19 characters - 15 = 4

Sin[t=π#/2]i+Cos@t&

This is an anonymous function, which you can use like

Sin[t=π#/2]i+Cos@t&[15]

(Or assign it to f say, and then do f[15].)

Supports reals and gives exact results for integer input.

Note that the i is not Mathematica's complex i (which is I). It's just an undefined variable.

Also, despite the order of the expression, Mathematica will reorder the output into R+Ci form.

Befunge-98, 41-5 = 36 35-5 = 30 32-5 = 27

&4%:01-`!4*+:2%'8*'1+\2/d*' +,,@

Supports negative integers. Not going to win any awards with this solution, but whatever.

It just accepts a number as input, does some trickery on the modulus (which, frustratingly, doesn't work like usual modulus for negative numbers in the interpreter I used to test it) to make negatives work, and then does some silly conditionals to decide what each character should be.

I'm sure this can be golfed down plenty further. For now, here's another solution that doesn't accept negatives, but makes up for the loss of the bonus by being shorter:

Befunge-98, 32 26 23

&4%:2%'8*'1+\2/d*' +,,@

Edit - Now takes advantage of the fact that "-" is 13 (0xd) characters away from " ".

Edit 2 - Now, again, takes advantage of the fact that "i" is 56 (0x38, or '8) characters away from "1".

Python 28 bytes - 5 = 23

Supports -ve inputs.

Assuming lambda functions are acceptable (Thanks FryAmTheEggman!):

lambda n:n%4/2*'-'+'1i'[n%2]

otherwise 31 bytes - 5 = 26

print[1,"i",-1,"-i"][input()%4]

JavaScript (ES6) 29-5 = 24

Supports negative power.

f=n=>(n&2?'-':'')+(n&1?'i':1)

ES5 :

function f(n){return (n&2?'-':'')+(n&1?'i':1)}

Perl, 26 - 5 = 21

say qw(1 i -1 -i)[pop()%4]

works as a standalone program (argument on the commandline) or the body of a function.

Haskell, 29 bytes - 5 = 24

f n=words"1 i -1 -i"!!mod n 4

Works for negative powers.

I had a pointfree version worked out, but it turns out it's actually longer.

f=(words"1 i -1 -i"!!).(`mod`4)

Ruby 32-5=27

puts(%w[1 i -1 -i][gets.to_i%4])

Works for negative powers!

Pure bash, 29 bytes - 5 = 24

Supports -ve inputs.

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