31
\$\begingroup\$

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!

\$\endgroup\$
15
  • 1
    \$\begingroup\$ In what format do we return exactly? Through function output or stdout? \$\endgroup\$ Commented Nov 21, 2014 at 15:59
  • 1
    \$\begingroup\$ @MartinBüttner but if i choose function output, how should the output should be formatted/stored without native complex numbers in my language? \$\endgroup\$ Commented Nov 21, 2014 at 16:02
  • 18
    \$\begingroup\$ @BetaDecay What are floating point integers? o.O \$\endgroup\$ Commented Nov 21, 2014 at 18:04
  • 2
    \$\begingroup\$ @MartinBüttner Haha wrong word :/ Floating point number then \$\endgroup\$
    – Beta Decay
    Commented Nov 21, 2014 at 18:17
  • 1
    \$\begingroup\$ I feel so stupid. I only just realized that python has a built in complex type. \$\endgroup\$
    – Justin
    Commented Nov 22, 2014 at 6:03

57 Answers 57

20
\$\begingroup\$

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).

\$\endgroup\$
3
  • 4
    \$\begingroup\$ "Ruby, -2 bytes"..... \$\endgroup\$
    – qqq
    Commented Dec 20, 2017 at 18:26
  • 5
    \$\begingroup\$ So, does downloading this 1,000,000,000,000 times give me 2TB of free hard drive space? Sounds like a good deal to me. \$\endgroup\$
    – rydwolf
    Commented Nov 15, 2019 at 21:29
  • 1
    \$\begingroup\$ ^ My browser broke down before I succeeded to do that. Maybe try a "zip bomb" with the file inside? (Extracting it saves space.) \$\endgroup\$
    – user85052
    Commented Nov 16, 2019 at 6:34
14
\$\begingroup\$

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.

\$\endgroup\$
9
  • \$\begingroup\$ You don't need the 4%. It can be done automatically. \$\endgroup\$
    – jimmy23013
    Commented Nov 21, 2014 at 16:45
  • \$\begingroup\$ @user23013 nifty :) \$\endgroup\$ Commented Nov 21, 2014 at 16:45
  • 9
    \$\begingroup\$ Shouldn't the two answers be separate? \$\endgroup\$
    – Justin
    Commented Nov 22, 2014 at 5:50
  • \$\begingroup\$ @Quincunx Maybe... originally they were both in CJam, which is why I put them in the same answer. But the second one wasn't valid, so I ported it to Mathematica, but left it where it was. If people insist I can split them up. \$\endgroup\$ Commented Nov 22, 2014 at 10:09
  • \$\begingroup\$ And you can save a character in using it with f@15 instead of f[15]. \$\endgroup\$
    – orome
    Commented Nov 22, 2014 at 23:35
14
\$\begingroup\$

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 ;)

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Doesn't the python lambda need to be assigned to a variable? At the vary least, to call it you'd need to surround it with parentheses, adding two bytes so it could be called (lambda...)(n). \$\endgroup\$
    – mbomb007
    Commented Mar 5, 2015 at 18:19
  • \$\begingroup\$ @mbomb007 According to meta this is acceptable. The code here creates a function that performs the task a required. Anonymous lambdas are used relatively frequently in python for functions like map and sorted. \$\endgroup\$ Commented Mar 5, 2015 at 19:38
11
\$\begingroup\$

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).

\$\endgroup\$
6
  • \$\begingroup\$ @MartinBüttner TI-Basic seems to use some kind of 'Expression' type, and the built-in methods return exact results for these. \$\endgroup\$
    – Shujal
    Commented Nov 21, 2014 at 20:34
  • \$\begingroup\$ I see, all good then. ;) \$\endgroup\$ Commented Nov 21, 2014 at 20:55
  • \$\begingroup\$ What about the rule "If your language supports complex numbers, don't use any functions or arithmetic that could work this out." +i is arithmetic \$\endgroup\$
    – edc65
    Commented Nov 21, 2014 at 21:33
  • \$\begingroup\$ @edc65 The + is actually a complex operation. However, if you don't like that, replace the with a normal i. If the variable i is not defined, you'll get the complex number, just with i instead of . I'm just calculating the real and imaginary parts separately. \$\endgroup\$
    – Shujal
    Commented Nov 21, 2014 at 21:54
  • 1
    \$\begingroup\$ @Shujal In that case, I think you should use i anyway. The complex i isn't even the character the question asks for, and it'll save you two bytes, so you'd at least tie with me ;). \$\endgroup\$ Commented Nov 21, 2014 at 22:30
7
\$\begingroup\$

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:

  • }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 nth 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.

\$\endgroup\$
16
  • 1
    \$\begingroup\$ I really like this one! Marbelous sounds fab I'll need to check it out sometime soon :) \$\endgroup\$
    – Kezz
    Commented Nov 21, 2014 at 23:14
  • 3
    \$\begingroup\$ @Kezz101 We've got a spec draft over here \$\endgroup\$ Commented Nov 21, 2014 at 23:15
  • \$\begingroup\$ Oh nice! It looks really interesting \$\endgroup\$
    – Kezz
    Commented Nov 21, 2014 at 23:17
  • \$\begingroup\$ Don't forget that you can give inputs to the main board on the command line, so this board could be used as-is. \$\endgroup\$
    – Sparr
    Commented Nov 22, 2014 at 3:32
  • 1
    \$\begingroup\$ @overactor Hm, I don't know... outputting additional characters (even if they're unprintable) still seems to violate the output format for me. Might be worth a meta question though. \$\endgroup\$ Commented Nov 24, 2014 at 10:39
6
\$\begingroup\$

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)}
\$\endgroup\$
3
  • \$\begingroup\$ Yep, shorter (f=n=>[1,'i',-1,'-i'][n%4]). But it's less sexy and it won't support negative powers. It depends on the bonus I guess. \$\endgroup\$
    – Michael M.
    Commented Nov 21, 2014 at 16:21
  • \$\begingroup\$ Nop, 29 bytes. Negative are supported with this code. \$\endgroup\$
    – Michael M.
    Commented Nov 21, 2014 at 16:25
  • \$\begingroup\$ Does JS have a bitwise & operator? If so you can do &3for a true modulus-4 operation. Edit: looks like it does as &2 is used in your answer... \$\endgroup\$
    – feersum
    Commented Nov 21, 2014 at 22:44
6
\$\begingroup\$

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)

\$\endgroup\$
5
\$\begingroup\$

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]
\$\endgroup\$
11
  • 1
    \$\begingroup\$ You can't call it exactly. You have to store it somewhere you can access. So you could do foo=..., or you could do map(<your lambda>,range(10)) to get a list of values of i^n from 0-9. \$\endgroup\$ Commented Nov 21, 2014 at 17:45
  • 2
    \$\begingroup\$ Basically you are making a function pointer, if that is more clear :P \$\endgroup\$ Commented Nov 21, 2014 at 17:46
  • 3
    \$\begingroup\$ @DigitalTrauma: Yes, although you may be able to do better with string slicing tricks. For example, lambda n:'--1i'[n%4-2::2]. \$\endgroup\$ Commented Nov 21, 2014 at 19:08
  • 2
    \$\begingroup\$ To translate user2357112's post: Take every other character from '--1i' starting at index n%4-2. When python gets a negative index, it will start that many positions left from the end of the array, and then go up to 0. This way, 0 and 1 don't ever hit the - signs, while 3 and 4 do. \$\endgroup\$ Commented Nov 21, 2014 at 21:01
  • 1
    \$\begingroup\$ lambda n:n%4/2*'-'+'1i'[n%2] Removes the space and is shorter :) \$\endgroup\$ Commented Nov 21, 2014 at 22:57
5
\$\begingroup\$

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!

\$\endgroup\$
4
\$\begingroup\$

(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)
\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ 29 - 5 = 24 bytes \$\endgroup\$
    – Giuseppe
    Commented Apr 18, 2019 at 17:55
  • \$\begingroup\$ @Giuseppe Totally blanked on that. My concern with that is that the output is technically mixed, half string, half numeric. \$\endgroup\$
    – Sumner18
    Commented Apr 18, 2019 at 18:00
  • 1
    \$\begingroup\$ nope, R automatically coerces numeric types to character when they're mixed! Hadley's book explains this pretty well -- just Ctrl + F to "Coercion" and you'll see it, but the whole book is worth a read (for non-golfing purposes mostly, but sometimes you pick up a trick or two, heheh) \$\endgroup\$
    – Giuseppe
    Commented Apr 18, 2019 at 18:03
4
\$\begingroup\$

PowerShell, 28 bytes -5 = 23

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

Try it online!

Port of all the cyclic indexing

\$\endgroup\$
3
\$\begingroup\$

Pure bash, 29 bytes - 5 = 24

Supports -ve inputs.

a=(1 i -1 -i)
echo ${a[$1%4]}
\$\endgroup\$
3
\$\begingroup\$

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".

\$\endgroup\$
3
\$\begingroup\$

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)

\$\endgroup\$
4
  • \$\begingroup\$ you could reduced your code, if you pass it to main as argument. \$\endgroup\$
    – user902383
    Commented Nov 24, 2014 at 13:04
  • \$\begingroup\$ @user902383 I could always make a function, indeed. Probably will post both versions, too. \$\endgroup\$ Commented Nov 24, 2014 at 14:04
  • \$\begingroup\$ actually i was thinking about parsing it, so you will have int n = Integer.parseInt(a[0]) \$\endgroup\$
    – user902383
    Commented Nov 24, 2014 at 14:09
  • \$\begingroup\$ @user902383 Daaaaamn, didn't even remember that. thumbs up \$\endgroup\$ Commented Nov 24, 2014 at 14:13
3
\$\begingroup\$

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"};

}
\$\endgroup\$
7
  • \$\begingroup\$ You can save some with "import java.util.*" \$\endgroup\$ Commented Nov 23, 2014 at 5:15
  • \$\begingroup\$ @Anubian Noob Class Function is in package java.util.function not java.util (or am I wrong?). \$\endgroup\$ Commented Nov 23, 2014 at 13:22
  • \$\begingroup\$ But if you do java.util.* the .* means import everything under the package. Just like you're currently importing all classes in the fuction package. \$\endgroup\$ Commented Nov 23, 2014 at 22:34
  • 5
    \$\begingroup\$ @ Anubian Noob import only imports the classes in that package. It does not import any of the classes from packages in that package. For example, class Function is in package java.util.function but not in package java.util. \$\endgroup\$ Commented Nov 23, 2014 at 23:17
  • \$\begingroup\$ Oh my bad, sorry about that. \$\endgroup\$ Commented Nov 24, 2014 at 4:29
3
\$\begingroup\$

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])
\$\endgroup\$
2
  • \$\begingroup\$ i^3 is -i, rather than i, guess it just adds 1 char. -- Sidenote for other readers: without the first rule of the challenge, the Matlab solution would only be 3 characters long. \$\endgroup\$ Commented Nov 24, 2014 at 16:43
  • \$\begingroup\$ Yes, that was a typo. Fixed! Thanks for noticing... At least the second (a bit more interesting) approach is correct =) \$\endgroup\$ Commented Nov 24, 2014 at 17:10
3
\$\begingroup\$

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]);}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ You can remove parentheses around n%2 and use ~ instead of ! because negating n first, then %ing with 2 will give the same result, at least for n<(1<<32)-1. And C doesn't require to explicitly define return type for function, so you can remove int at the beginning. And also use 0 instead of '\0'. Thus -9 chars. \$\endgroup\$
    – Ruslan
    Commented Nov 23, 2014 at 14:33
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

Husk, (14 11 bytes - 5) = 6

Edit: -3 bytes thanks to Razetime

!C2¨¹-1-i 1

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ you can remove the %4⁰. \$\endgroup\$
    – Razetime
    Commented Apr 7, 2021 at 7:09
3
\$\begingroup\$

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)
\$\endgroup\$
2
  • \$\begingroup\$ I think you've got it the wrong way round: \$i^0 = 1\$, not \$i\$. Fix it like this. \$\endgroup\$
    – The Thonnu
    Commented Jun 25, 2023 at 16:59
  • 1
    \$\begingroup\$ @TheThonnu Wait, you're completely right.. I must have accidently swapped your and my own test suite when I checked with the four provided test cases in the challenge description earlier today.. So sorry, my bad. Weird how no one noticed my mistake back in 2019 (including myself).. :/ Thanks for the fix. And how it also works for \$i^0\$ I guess, even though it's a bonus instead of necessity. :) \$\endgroup\$ Commented Jun 25, 2023 at 23:02
2
\$\begingroup\$

Ruby 32-5=27

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

Works for negative powers!

\$\endgroup\$
1
  • \$\begingroup\$ You can trivially golf this more with puts %w[1 i -1 i][gets.to_i % 4]. \$\endgroup\$
    – histocrat
    Commented Nov 21, 2014 at 20:05
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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]
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ "If your language supports complex numbers, don't use any functions or arithmetic that could work this out." I think it's pretty clear... \$\endgroup\$ Commented Dec 20, 2017 at 18:17
  • \$\begingroup\$ @totallyhuman Well, I'm not sure if the 1j literal is banned either though? \$\endgroup\$ Commented Dec 20, 2017 at 18:22
  • \$\begingroup\$ Yeah, but the arithmetic (*) is. \$\endgroup\$ Commented Dec 20, 2017 at 18:22
  • 1
    \$\begingroup\$ @totallyhuman Hm, maybe I'll add another version below, although "don't use any functions or arithmetic that could work this out" seems to suggest that I can't use a built-in to do this exact task...BTW the way he phrases it gets me to think that you're encouraged to use 1j literals. \$\endgroup\$ Commented Dec 20, 2017 at 18:24
2
\$\begingroup\$

Swift, 27

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

Try it online

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$
    – alephalpha
    Commented Apr 18, 2019 at 14:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.