[Question]
  [
**The Challenge**
In as few characters as possible, find the value of \$i^n\$, given \$n\$, a positive integer greater than 0. This should be outputted as a String.
For those that don't know, \$i\$ is defined such that \$i^2=-1\$. So:
* \$i^1=i\$
* \$i^2=-1\$
* \$i^3=-i\$
* \$i^4=1\$
This then repeats..
**Rules**
* If your language supports complex numbers, don't use any functions or arithmetic that could work this out.
* Floating point inaccuracies are fine for answers that would return decimals anyway, but integer inputs should give exact results
**Bonus Points**
-5 if you can work the value out where n is also negative
-15 if you can work out the value for any real number (this bonus includes the -5 from the above bonus)
Good luck!
  
[Answer]
# 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).
[Answer]
# CJam, 12 characters - 5 = 7
```
1'iW"-i"]li=
```
[Test it here.](http://cjam.aditsu.net/)
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.
[Answer]
## 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](https://codegolf.stackexchange.com/a/41726/31625) 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](https://github.com/isaacg1/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.](https://pyth.herokuapp.com/)
I'm going to go have a talk with isaacg about Pyth indexing ;)
[Answer]
## 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).
[Answer]
# [Marbelous](https://codegolf.stackexchange.com/a/40808/8478), 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:
* `}0` is where the first command-line argument goes. I've used two instances of this device, so I get two copies of the input value (at the same time).
* `^n` checks for the `n`th bit of the input marble (where `n=0` is the least significant bit), and produces `1` or `0` depending on the bit.
* `=0` checks for equality with `0`. If the input marble is equal, it just drops straight through, if it isn't it is pushed to the right.
* `\/` is a trash can, so it just swallows the input marble and never produces anything.
* `2D` is the ASCII code of `-`, `31` is the ASCII code of `1` and `69` is the ASCII code of `i`.
* The `&n` are synchronisers. Synchronisers stall a marble until all synchronisers with the same `n` hold a marble, at which point they'll all let their stored marble fall through.
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](https://github.com/marbelous-lang/docs/blob/master/spec-draft.md).
[Answer]
# 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)}
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 8 chars - 15 bonus = score -7
The built-in (and thus prohibited) function is `0J1*‚ä¢`, but this uses [@blutorange's method](https://codegolf.stackexchange.com/a/47446/43319).
```
¬Ø12‚óã.5√ó‚óã
```
The challenge author, Kezz101, [wrote](https://codegolf.stackexchange.com/questions/41719/find-in-given-n#comment97114_41719):
> 
> 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!](https://tio.run/##SyzI0U2pTMzJT///PzMgvzy16FHbhEPrDY0eTe/WMz08HUj9dyutqoKIplpmgUltEAtEP@papPCod65CempJsUJRZopCfppCWk5@YklmXrpCQX5mXolCalFRflEx2BAFiA0KhgpGCsYKJgqmXMiiQJOB2AiIjYHYBIhR5Q30DIHYCIiNgdgEiE0B "APL (Dyalog Unicode) ‚Äì 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)
[Answer]
# 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]
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 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!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y4zLk9VIzPOSNtQ839afpFGHlBc19BARwGEFQqKMvNKgGJKCrp2QCJNI09TU/M/AA "Pari/GP ‚Äì Try It Online")
[Answer]
# (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)
```
[Answer]
# [R](https://www.r-project.org/), 29 - 5 = 24 bytes
```
c(1,"i",-1,"-i")[scan()%%4+1]
```
[Try it online!](https://tio.run/##K/r/P1nDUEcpU0lHF0jpZippRhcnJ@ZpaKqqmmgbxv435DLiMuYy4TLlMuMy57Lg@g8A "R ‚Äì 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.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 28 bytes -5 = 23
```
('i',-1,'-i',1)["$args"%4-1]
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V9DPVNdR9dQR10XSBtqRiupJBalFyupmugaxv6v5eLSNTTQ0zM0qFGtVlKJV7BSUNFQU0lTUInXVKr9DwA "PowerShell ‚Äì Try It Online")
Port of all the cyclic indexing
[Answer]
# Pure bash, 29 bytes - 5 = 24
Supports -ve inputs.
```
a=(1 i -1 -i)
echo ${a[$1%4]}
```
[Answer]
# 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".
[Answer]
# 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)
[Answer]
# **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"};
}
```
[Answer]
# 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])
```
[Answer]
# 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]);}
```
[Answer]
# 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.
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), [13 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) - 5 = 8
```
‚óÑ≈°<f5¬Æ‚Ä¶‚îò‚î§√Ø\√é¬±
```
[Try it!](https://zippymagician.github.io/Arn?code=WzEiaSJuXzEiLWkiXT8lNA==&input=LTQKLTMKLTIKLTEKMQoyCjMKNA==)
# 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
```
[Answer]
# [Scala](http://www.scala-lang.org/), 7 bytes - 15 = -8
Port of [@blutorange's](https://codegolf.stackexchange.com/users/26465/blutorange) devious [Ruby answer](https://codegolf.stackexchange.com/a/47446/95792). Go upvote that!
```
1->_*90
```
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUM1VlpijkGal4JSZ7pKanJkL5NnaKWh45pXoIIQ0FWz/G@raxWtZGvwvKMrMK8nJ00jTMNTU5ELwjFB4uYklGXoBmShiuqZAbu1/AA "Scala ‚Äì 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!](https://tio.run/##Vcm9CsIwFMXxvU9xxlbUquCgoiC4Cg6@wG1zQyNpEpLrB4jPHh1E7HZ@559aspR9c@FWcCTjwA9hpxL2IeBZ3MhCr3Hw18YytrvfyqvZKG9Q12ePxIEiCcMIdPQ9QjROrBvDeYFjVqzgpeN4N4mLby11Oa@qPy0G6km66ckMvsnyw1d@Aw "Scala ‚Äì 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!](https://tio.run/##DctBCsIwEAXQfU/xKQiJEGiKK7EFly668gAytomMhiSkQxHEs0ff/q0zBarp/nSzYCKOcG9xcVlxzhmfZqMAf8QlCoYRVykcHxhqCws21nC7lJRx2x32PYReDn31qUAxTgYdJMF2GvnfJETlFWvdfOsP "Scala ‚Äì Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), (30 bytes - 15) = 15
```
m‚ÇÅm*1.57·π†e-1
Œ£z*ƒ∞_m¬ß/Œ†`^‚Å∞‚Üë99ƒ∞1
```
[Try it online!](https://tio.run/##AUYAuf9odXNr/20oLzEwMMO3MSoxMDAp4oKB/23igoJtKjEuNTfhuaBlLTEKzqN6KsSwX23Cpy/OoGBe4oGw4oaROTnEsDH///81 "Husk ‚Äì 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](https://github.com/barbuz/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](https://en.wikipedia.org/wiki/Sine#Series_definition)), and use `1.57` as a very rough approximation for pi/2.
To make matters even more difficult, [Husk](https://github.com/barbuz/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](https://tio.run/##AUEAvv9odXNr//9tyK8vMTDDtzEqMTBt4oKBbSoxLjU34bmgZS0xCs6jeirEsF9twqcvzqBgXuKBsOKGkTk5xLAx////NQ) to include it.
[Answer]
# [Husk](https://github.com/barbuz/Husk), (~~14~~ 11 bytes - 5) = 6
*Edit: -3 bytes thanks to Razetime*
```
!C2¬®¬π-1-i 1
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8b@is9GhFYd26hrqZioY/v//P1rXSEfXUMdAx1DHSMdYxyQWAA "Husk ‚Äì Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score 5 (10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) - 5 bonus)
```
1'i¬Æ‚Äû-i)I√®
```
[Try it online](https://tio.run/##yy9OTMpM/f/fUD3z0LpHDfN0MzU9D6/4/1/XEAA) or [verify some more test cases](https://tio.run/##yy9OTMpM/R@iEXJ0R1mlvZLCo7ZJCkr2/w3VMw@te9QwTzdTs/Lwiv86/wE).
**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)
```
[Answer]
# Ruby 32-5=27
```
puts(%w[1 i -1 -i][gets.to_i%4])
```
Works for negative powers!
[Answer]
## 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.
[Answer]
## 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.
[Answer]
# 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]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 - 20 = -18 bytes
```
ƒ±*
```
[Try it online!](https://tio.run/##y0rNyan8///IRq3///@b6hkDAA "Jelly ‚Äì Try It Online")
It doesn't use an `i ^ x` builtin but it uses builtins for `1j` and `**` so not sure if allowed.
[Answer]
## Swift, 27
```
{["1","i","-1","-i"][$0%4]}
```
[Try it online](https://tio.run/##Ky7PTCsx@Z@TWqKQbKWg4ZlXoqmga6cQXFKUmZeuYPu/OlrJUElHKROIdUEM3Uyl2GgVA1WT2Nr/GgZ6enqGBpp6aflFronJGQrVCgVAbSUayRoqBpqaCrX/AQ)
]