Find i^n, given n

27

1

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!

Kezz101

Posted 2014-11-21T15:43:53.413

Reputation: 405

1In what format do we return exactly? Through function output or stdout? – proud haskeller – 2014-11-21T15:59:36.040

@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. – Martin Ender – 2014-11-21T16:00:54.357

1@MartinBüttner but if i choose function output, how should the output should be formatted/stored without native complex numbers in my language? – proud haskeller – 2014-11-21T16:02:50.550

If you support any real number you can output in any valid complex form. So just 1 would be valid and so would 1+0i. – Kezz101 – 2014-11-21T16:31:00.210

Well I think that floating point inaccuracies are fine for answers that would return decimals anyway, but integer inputs should give exact results. (This is my first question posed so if you disagree let me know!) – Kezz101 – 2014-11-21T17:23:20.430

Okay, I shall do! – Kezz101 – 2014-11-21T17:42:07.677

Do we require the use of floating point integers? – Beta Decay – 2014-11-21T17:58:15.357

16@BetaDecay What are floating point integers? o.O – Martin Ender – 2014-11-21T18:04:23.263

2@MartinBüttner Haha wrong word :/ Floating point number then – Beta Decay – 2014-11-21T18:17:18.337

Common Lisp, (26 characters - 15 = 11): (lambda(n)(expt #C(0 1)n)). Unfortunately, this is against the rules :-( – coredump – 2014-11-21T19:12:51.323

I feel so stupid. I only just realized that python has a built in complex type. – Justin – 2014-11-22T06:03:00.583

i is not defined as the square root of -1. Rather, it is defined such that i^2 = -1, which is not the same, since one can choose plus or minus the root of -1. – user1997744 – 2014-11-22T18:12:57.867

@user1997744 True, I'll edit it now although I doubt it'll make any difference.. – Kezz101 – 2014-11-22T18:16:22.270

mod 4 and a lookup. This doesn't seem very interesting. – Tim Seguine – 2014-11-24T13:58:48.233

@user1997744 in all fairness, it is possible to define square root that way as well, making it unique by taking a branch cut. – Tim Seguine – 2014-11-24T14:01:08.783

Answers

15

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

blutorange

Posted 2014-11-21T15:43:53.413

Reputation: 1 205

4"Ruby, -2 bytes"..... – FantaC – 2017-12-20T18:26:24.407

3So, does downloading this 1,000,000,000,000 times give me 2TB of free hard drive space? Sounds like a good deal to me. – Redwolf Programs – 2019-11-15T21:29:05.490

^ My browser broke down before I succeeded to do that. Maybe try a "zip bomb" with the file inside? (Extracting it saves space.) – None – 2019-11-16T06:34:31.177

15

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.

Martin Ender

Posted 2014-11-21T15:43:53.413

Reputation: 184 808

You don't need the 4%. It can be done automatically. – jimmy23013 – 2014-11-21T16:45:20.223

@user23013 nifty :) – Martin Ender – 2014-11-21T16:45:46.507

8Shouldn't the two answers be separate? – Justin – 2014-11-22T05:50:26.687

@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. – Martin Ender – 2014-11-22T10:09:50.207

And you can save a character in using it with f@15 instead of f[15]. – orome – 2014-11-22T23:35:01.070

@raxacoricofallapatorius I'm not counting that. The byte count is only for the function definition, not for using it. – Martin Ender – 2014-11-22T23:35:52.200

@MartinBüttner: Yep, I know. Just pointing out that using it is brief too. – orome – 2014-11-22T23:37:28.330

You can also change Pi to π to save a char – miles – 2014-11-23T12:40:35.560

@miles Oh right, I somehow thought scoring is in bytes, but the question mentions characters, yay! :) – Martin Ender – 2014-11-23T13:03:46.713

14

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

FryAmTheEggman

Posted 2014-11-21T15:43:53.413

Reputation: 16 206

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). – mbomb007 – 2015-03-05T18:19:29.940

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

– FryAmTheEggman – 2015-03-05T19:38:55.980

11

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

Shujal

Posted 2014-11-21T15:43:53.413

Reputation: 687

@MartinBüttner TI-Basic seems to use some kind of 'Expression' type, and the built-in methods return exact results for these. – Shujal – 2014-11-21T20:34:27.423

I see, all good then. ;) – Martin Ender – 2014-11-21T20:55:57.623

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 – edc65 – 2014-11-21T21:33:45.040

@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. – Shujal – 2014-11-21T21:54:46.470

1@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 ;). – Martin Ender – 2014-11-21T22:30:08.497

Scoring is in characters, so that's 20 characters/score 5 for you. – Martin Ender – 2014-11-23T13:05:24.337

7

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.

Martin Ender

Posted 2014-11-21T15:43:53.413

Reputation: 184 808

1I really like this one! Marbelous sounds fab I'll need to check it out sometime soon :) – Kezz101 – 2014-11-21T23:14:37.983

3

@Kezz101 We've got a spec draft over here

– Martin Ender – 2014-11-21T23:15:20.350

Oh nice! It looks really interesting – Kezz101 – 2014-11-21T23:17:53.220

Don't forget that you can give inputs to the main board on the command line, so this board could be used as-is. – Sparr – 2014-11-22T03:32:38.933

@Sparr Yes, but supplying small bytes via command line argument is annoying. – Martin Ender – 2014-11-22T10:10:36.213

@MartinBüttner I'm pretty sure that command line "1" is marble 0x01 – Sparr – 2014-11-22T19:57:26.413

@Sparr Oh okay, I thought command-line arguments were read like STDIN, byte-for-byte. – Martin Ender – 2014-11-22T19:57:58.907

@MartinBüttner You can ditch the last row, saving 3 bytes, you'll be printing zero width characters, but I doubt that that's a problem. – overactor – 2014-11-24T08:51:02.350

1@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. – Martin Ender – 2014-11-24T10:39:16.490

I feel like you could stack things differently and save a line here. Will the two processing chains (below the two duped inputs) fit side by side in any way? – Sparr – 2014-11-24T16:07:15.783

@Sparr maybe with cylindrical boards? – Martin Ender – 2014-11-24T16:11:08.597

I think you need another / under the first &0 to avoid dropping a 0x01 to stdout before a "-" – Sparr – 2014-11-24T16:49:24.877

here's my test harness, if it's useful: for i in 1 2 3 4; do marbelous.py powersofi.mbl $i | hexdump -C ; done – Sparr – 2014-11-24T16:50:02.530

@Sparr ah, you're right. I think I've fixed it without using extra characters. – Martin Ender – 2014-11-24T16:51:06.077

@MartinBüttner now the matble in the upper &2 synchronizer is falling through and triggering the &0, causing you to print -i in stead of i for input%4 == 1. – overactor – 2014-11-25T07:04:27.230

@overactor oh right, I should probably terminate the board instead. Will test later. – Martin Ender – 2014-11-25T09:39:07.767

6

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

Michael M.

Posted 2014-11-21T15:43:53.413

Reputation: 12 173

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. – Michael M. – 2014-11-21T16:21:41.983

Nop, 29 bytes. Negative are supported with this code. – Michael M. – 2014-11-21T16:25:11.197

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... – feersum – 2014-11-21T22:44:41.230

5

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]

Digital Trauma

Posted 2014-11-21T15:43:53.413

Reputation: 64 644

:) Also, if you are allowed to use anonymous lambdas (I think the meta consensus was yes...) lambda n:[1,"i",-1,"-i"][n%4] is shorter – FryAmTheEggman – 2014-11-21T17:42:17.150

@FryAmTheEggman I'm a python noob. How do I call such a thing? – Digital Trauma – 2014-11-21T17:43:47.303

1You 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. – FryAmTheEggman – 2014-11-21T17:45:42.493

2Basically you are making a function pointer, if that is more clear :P – FryAmTheEggman – 2014-11-21T17:46:58.213

You're supposed to output a string. – user2357112 supports Monica – 2014-11-21T19:00:51.387

@user2357112 I assume the print version is fine. Are you saying I should quote the 1 and -1 in the lambda version? – Digital Trauma – 2014-11-21T19:05:27.177

3@DigitalTrauma: Yes, although you may be able to do better with string slicing tricks. For example, lambda n:'--1i'[n%4-2::2]. – user2357112 supports Monica – 2014-11-21T19:08:40.950

@user2357112 - thats cool, though I feel guilty taking that as my best answer as I still don't fully understand what you did, and certainly wouldn't have come up with it myself. If you make your own answer with this I'll upvote for sure. Meanwhile I added my best effort which returns strings (and a leading space unfortunately) – Digital Trauma – 2014-11-21T19:20:12.827

2To 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. – FryAmTheEggman – 2014-11-21T21:01:26.633

1lambda n:n%4/2*'-'+'1i'[n%2] Removes the space and is shorter :) – FryAmTheEggman – 2014-11-21T22:57:12.933

1@user2357112 Very clever! Another char off: '--i1'[~n%4::2]. – xnor – 2014-11-22T00:07:48.567

4

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)

Adám

Posted 2014-11-21T15:43:53.413

Reputation: 37 779

4

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

Sean Allred

Posted 2014-11-21T15:43:53.413

Reputation: 141

3

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!

alephalpha

Posted 2014-11-21T15:43:53.413

Reputation: 23 988

3

Pure bash, 29 bytes - 5 = 24

Supports -ve inputs.

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

Digital Trauma

Posted 2014-11-21T15:43:53.413

Reputation: 64 644

3

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

Kasran

Posted 2014-11-21T15:43:53.413

Reputation: 681

3

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

Stewie Griffin

Posted 2014-11-21T15:43:53.413

Reputation: 43 471

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. – Dennis Jaheruddin – 2014-11-24T16:43:29.573

Yes, that was a typo. Fixed! Thanks for noticing... At least the second (a bit more interesting) approach is correct =) – Stewie Griffin – 2014-11-24T17:10:16.233

3

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

}

TheNumberOne

Posted 2014-11-21T15:43:53.413

Reputation: 10 855

You can save some with "import java.util.*" – Anubian Noob – 2014-11-23T05:15:21.943

@Anubian Noob Class Function is in package java.util.function not java.util (or am I wrong?). – TheNumberOne – 2014-11-23T13:22:34.250

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. – Anubian Noob – 2014-11-23T22:34:25.010

5@ 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. – TheNumberOne – 2014-11-23T23:17:40.363

Oh my bad, sorry about that. – Anubian Noob – 2014-11-24T04:29:04.220

I soooo have to update my Java skills :/ – Rodolfo Dias – 2014-11-24T14:18:39.323

I don't think the challenge requires a class declaration. – Ypnypn – 2014-11-24T14:41:40.253

3

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

Rames

Posted 2014-11-21T15:43:53.413

Reputation: 221

2You 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. – Ruslan – 2014-11-23T14:33:32.773

3

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.

usernumber

Posted 2014-11-21T15:43:53.413

Reputation: 131

2

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.

Sumner18

Posted 2014-11-21T15:43:53.413

Reputation: 1 334

29 - 5 = 24 bytes – Giuseppe – 2019-04-18T17:55:18.587

@Giuseppe Totally blanked on that. My concern with that is that the output is technically mixed, half string, half numeric. – Sumner18 – 2019-04-18T18:00:47.607

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)

– Giuseppe – 2019-04-18T18:03:37.820

2

PowerShell, 28 bytes -5 = 23

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

Try it online!

Port of all the cyclic indexing

Veskah

Posted 2014-11-21T15:43:53.413

Reputation: 3 580

2

Ruby 32-5=27

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

Works for negative powers!

MegaTom

Posted 2014-11-21T15:43:53.413

Reputation: 3 787

You can trivially golf this more with puts %w[1 i -1 i][gets.to_i % 4]. – histocrat – 2014-11-21T20:05:12.747

2

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.

hobbs

Posted 2014-11-21T15:43:53.413

Reputation: 2 403

2

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)

Rodolfo Dias

Posted 2014-11-21T15:43:53.413

Reputation: 3 940

you could reduced your code, if you pass it to main as argument. – user902383 – 2014-11-24T13:04:39.743

@user902383 I could always make a function, indeed. Probably will post both versions, too. – Rodolfo Dias – 2014-11-24T14:04:19.223

actually i was thinking about parsing it, so you will have int n = Integer.parseInt(a[0]) – user902383 – 2014-11-24T14:09:58.383

@user902383 Daaaaamn, didn't even remember that. thumbs up – Rodolfo Dias – 2014-11-24T14:13:00.507

2

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.

kukac67

Posted 2014-11-21T15:43:53.413

Reputation: 2 159

2

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]

Rentsy

Posted 2014-11-21T15:43:53.413

Reputation: 151

1

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.

Erik the Outgolfer

Posted 2014-11-21T15:43:53.413

Reputation: 38 134

"If your language supports complex numbers, don't use any functions or arithmetic that could work this out." I think it's pretty clear... – totallyhuman – 2017-12-20T18:17:50.767

@totallyhuman Well, I'm not sure if the 1j literal is banned either though? – Erik the Outgolfer – 2017-12-20T18:22:20.107

Yeah, but the arithmetic (*) is. – totallyhuman – 2017-12-20T18:22:45.497

1@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. – Erik the Outgolfer – 2017-12-20T18:24:53.127

1

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)

Kevin Cruijssen

Posted 2014-11-21T15:43:53.413

Reputation: 67 575

1

Swift, 27

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

Try it online

ielyamani

Posted 2014-11-21T15:43:53.413

Reputation: 111

1Welcome to PPCG! – alephalpha – 2019-04-18T14:11:01.723

1

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!

bb94

Posted 2014-11-21T15:43:53.413

Reputation: 1 831

1

C (gcc), 30 bytes

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

Try it online!

ceilingcat

Posted 2014-11-21T15:43:53.413

Reputation: 5 503

1

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.

ceilingcat

Posted 2014-11-21T15:43:53.413

Reputation: 5 503

1

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)

colevk

Posted 2014-11-21T15:43:53.413

Reputation: 225

1

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

bacchusbeale

Posted 2014-11-21T15:43:53.413

Reputation: 1 235

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';. – Ruslan – 2014-11-23T14:20:39.447

@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. – bacchusbeale – 2014-11-25T06:13:25.607

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. – Ruslan – 2014-11-25T06:18:51.503

1

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.

Bob Jarvis - Reinstate Monica

Posted 2014-11-21T15:43:53.413

Reputation: 544

Instead of using a select structure, can't you use some sort of explicit array as in my answer?

– Sean Allred – 2014-11-24T01:22:06.400

1

Groovy: 27-5 = 22

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

Armand

Posted 2014-11-21T15:43:53.413

Reputation: 499

1

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.

Charles

Posted 2014-11-21T15:43:53.413

Reputation: 2 435

0

Java (OpenJDK 8), 39 bytes

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

Try it online!

Xanderhall

Posted 2014-11-21T15:43:53.413

Reputation: 1 236

0

Haskell, 27 bytes

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

Try it online!

totallyhuman

Posted 2014-11-21T15:43:53.413

Reputation: 15 378

0

Tcl, 50 bytes

proc I n {expr $n%4==3?"-i":$n%4==2?-1:$n%4?"i":1}

Try it online!

sergiol

Posted 2014-11-21T15:43:53.413

Reputation: 3 055

0

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.

Magic Octopus Urn

Posted 2014-11-21T15:43:53.413

Reputation: 19 422

0

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

reffu

Posted 2014-11-21T15:43:53.413

Reputation: 1 361

0

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:

  • %4 results in a value in the range -3 to 3 (negative inputs give negative outputs), so we shift up with +5.
  • Arrays are 1-indexed, hence +5 instead of +4.
  • We make our array twice as long by using brace expansion: {,}foo expands to foo foo.

GammaFunction

Posted 2014-11-21T15:43:53.413

Reputation: 2 838

0

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.

Lyxal

Posted 2014-11-21T15:43:53.413

Reputation: 5 253

You program supports negative numbers, you should have the -5 bonus! -5 if you can work the value out where n is also negative – None – 2019-11-16T06:09:58.743

0

C# 69-5 = 64

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

binderbound

Posted 2014-11-21T15:43:53.413

Reputation: 111

I have asked a question on meta about this answer: http://meta.codegolf.stackexchange.com/questions/4851/are-c-linqpad-answers-encouraged

– Thomas Weller – 2015-03-05T22:27:59.750

output is in form -1i, 1i, i, or 1 – binderbound – 2014-11-23T23:38:01.870

1You cannot claim the -15 bonus as this would fail on the input 3.247104. You may only claim the -5 bonus. – Beta Decay – 2014-11-24T07:06:53.213

Oh, sorry, yes - I didn't read the bonuses bit properly – binderbound – 2014-11-27T03:34:29.997

0

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

Danieth

Posted 2014-11-21T15:43:53.413

Reputation: 101

l.call(t)l[t]. Read Tips for golfing in Ruby for more. – manatwork – 2015-12-04T06:43:27.063

0

C, 61

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

Try it here.

Cole Cameron

Posted 2014-11-21T15:43:53.413

Reputation: 1 013