25
\$\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\$
  • 1
    \$\begingroup\$ In what format do we return exactly? Through function output or stdout? \$\endgroup\$ – proud haskeller Nov 21 '14 at 15:59
  • \$\begingroup\$ @proudhaskeller The tag wiki lists defaults for that. Unless specified otherwise, functions and programs are fine, input via function argument, STDIN or command-line argument and output via STDOUT or function return value. Functions do not have to be named. \$\endgroup\$ – Martin Ender Nov 21 '14 at 16:00
  • 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\$ – proud haskeller Nov 21 '14 at 16:02
  • 16
    \$\begingroup\$ @BetaDecay What are floating point integers? o.O \$\endgroup\$ – Martin Ender Nov 21 '14 at 18:04
  • 2
    \$\begingroup\$ @MartinBüttner Haha wrong word :/ Floating point number then \$\endgroup\$ – Beta Decay Nov 21 '14 at 18:17

41 Answers 41

11
\$\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\$
  • 2
    \$\begingroup\$ "Ruby, -2 bytes"..... \$\endgroup\$ – FantaC Dec 20 '17 at 18:26
15
\$\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\$
  • \$\begingroup\$ You don't need the 4%. It can be done automatically. \$\endgroup\$ – jimmy23013 Nov 21 '14 at 16:45
  • \$\begingroup\$ @user23013 nifty :) \$\endgroup\$ – Martin Ender Nov 21 '14 at 16:45
  • 8
    \$\begingroup\$ Shouldn't the two answers be separate? \$\endgroup\$ – Justin Nov 22 '14 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\$ – Martin Ender Nov 22 '14 at 10:09
  • \$\begingroup\$ And you can save a character in using it with f@15 instead of f[15]. \$\endgroup\$ – orome Nov 22 '14 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\$
  • \$\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 Mar 5 '15 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\$ – FryAmTheEggman Mar 5 '15 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\$
  • \$\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 Nov 21 '14 at 20:34
  • \$\begingroup\$ I see, all good then. ;) \$\endgroup\$ – Martin Ender Nov 21 '14 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 Nov 21 '14 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 Nov 21 '14 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\$ – Martin Ender Nov 21 '14 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\$
  • 1
    \$\begingroup\$ I really like this one! Marbelous sounds fab I'll need to check it out sometime soon :) \$\endgroup\$ – Kezz101 Nov 21 '14 at 23:14
  • 3
    \$\begingroup\$ @Kezz101 We've got a spec draft over here \$\endgroup\$ – Martin Ender Nov 21 '14 at 23:15
  • \$\begingroup\$ Oh nice! It looks really interesting \$\endgroup\$ – Kezz101 Nov 21 '14 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 Nov 22 '14 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\$ – Martin Ender Nov 24 '14 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\$
  • \$\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. Nov 21 '14 at 16:21
  • \$\begingroup\$ Nop, 29 bytes. Negative are supported with this code. \$\endgroup\$ – Michael M. Nov 21 '14 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 Nov 21 '14 at 22:44
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\$
  • 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\$ – FryAmTheEggman Nov 21 '14 at 17:45
  • 2
    \$\begingroup\$ Basically you are making a function pointer, if that is more clear :P \$\endgroup\$ – FryAmTheEggman Nov 21 '14 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\$ – user2357112 Nov 21 '14 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\$ – FryAmTheEggman Nov 21 '14 at 21:01
  • 1
    \$\begingroup\$ lambda n:n%4/2*'-'+'1i'[n%2] Removes the space and is shorter :) \$\endgroup\$ – FryAmTheEggman Nov 21 '14 at 22:57
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\$
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 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\$
  • \$\begingroup\$ You can save some with "import java.util.*" \$\endgroup\$ – Anubian Noob Nov 23 '14 at 5:15
  • \$\begingroup\$ @Anubian Noob Class Function is in package java.util.function not java.util (or am I wrong?). \$\endgroup\$ – TheNumberOne Nov 23 '14 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\$ – Anubian Noob Nov 23 '14 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\$ – TheNumberOne Nov 23 '14 at 23:17
  • \$\begingroup\$ Oh my bad, sorry about that. \$\endgroup\$ – Anubian Noob Nov 24 '14 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\$
  • \$\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\$ – Dennis Jaheruddin Nov 24 '14 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\$ – Stewie Griffin Nov 24 '14 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\$
  • 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 Nov 23 '14 at 14:33
3
\$\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\$
2
\$\begingroup\$

Ruby 32-5=27

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

Works for negative powers!

\$\endgroup\$
  • \$\begingroup\$ You can trivially golf this more with puts %w[1 i -1 i][gets.to_i % 4]. \$\endgroup\$ – histocrat Nov 21 '14 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\$

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

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

Pari/GP, 19 bytes - 5 = 14

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

n->Str(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\$
1
\$\begingroup\$

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

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.

\$\endgroup\$
  • \$\begingroup\$ Instead of using a select structure, can't you use some sort of explicit array as in my answer? \$\endgroup\$ – Sean Allred Nov 24 '14 at 1:22
1
\$\begingroup\$

Groovy: 27-5 = 22

f={n->[1,'i',-1,'-i'][n%4]}
\$\endgroup\$
1
\$\begingroup\$

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);
}
\$\endgroup\$
  • \$\begingroup\$ It doesn't even compile because you must parenthesize the assignments after : in ?: statements in plain C. Also, what's the point of using 0==0 when you can use single char 1? And no need in parentheses before ?. Also, the last ?: statement could be shortened to c[j]=i&1?'i':'1';. \$\endgroup\$ – Ruslan Nov 23 '14 at 14:20
  • \$\begingroup\$ @Ruslan In CodeBlocks Mingw there is only 1 warning around i&0. i&0==0 is a test for even, if i is even the result is 0 else it is 1. \$\endgroup\$ – bacchusbeale Nov 25 '14 at 6:13
  • \$\begingroup\$ Yeah, but what's the point of using 0==0 when it's identical to 1? Note that == has higher precedence than &, otherwise your (supposed) test of (i&0)==0 would always be true. \$\endgroup\$ – Ruslan Nov 25 '14 at 6:18
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

'i®„-i1)Iè

Try it online or verify some more test cases.

Explanation:

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

Swift, 27

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

Try it online

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – alephalpha Apr 18 at 14:11
1
\$\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\$
  • \$\begingroup\$ 29 - 5 = 24 bytes \$\endgroup\$ – Giuseppe Apr 18 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 Apr 18 at 18:00
  • \$\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 Apr 18 at 18:03
0
\$\begingroup\$

C# 69-5 = 64

public string m(int n){return n%2==0?(n%4==0?"1":"-1"):(m(n-1)+"i");}
\$\endgroup\$
  • \$\begingroup\$ output is in form -1i, 1i, i, or 1 \$\endgroup\$ – binderbound Nov 23 '14 at 23:38
  • 1
    \$\begingroup\$ You cannot claim the -15 bonus as this would fail on the input 3.247104. You may only claim the -5 bonus. \$\endgroup\$ – Beta Decay Nov 24 '14 at 7:06
  • \$\begingroup\$ Oh, sorry, yes - I didn't read the bonuses bit properly \$\endgroup\$ – binderbound Nov 27 '14 at 3:34
  • \$\begingroup\$ I have asked a question on meta about this answer: meta.codegolf.stackexchange.com/questions/4851/… \$\endgroup\$ – Thomas Weller Mar 5 '15 at 22:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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