Your code has to provide the following functions:


Reads a complex number from the standard input. It has to accept and evaluate something in the form of for example 1.42 + 3i.


Prints the complex number in the form of, for example 1.23 - 4.32i


Adds, subtracts, multiplies and respectively divides the two complex numbers.

It is enough if your functions are accurate to two digits after the decimal point, of course, it can be more if you so wish. The input will never have more than two digits after the decimal point.

Any language without native support for complex numbers may be used. Similarly, libraries or other language features which deal with complex numbers are not permitted. The point is, you have to do all the handling of complex numbers by yourself.


This is a code golf. The score is the sum of the lengths of the function bodies. For example, int add(int a, int b) {return a+b;} will have a length of 11 because of return a+b. Your solution must have a main program which demonstrates the use of the functions (for easier evaluation of your solution), but it will not be part of the scoring.

You can store the complex numbers in any way you wish, but the functions must have exactly the same amount of parameters as in the above description.

EDIT: For languages that support it, you can use operator overloading instead of the add, sub, etc. functions.

EDIT 2: To prohibit the cheap #define all_your_code_here A, I'll try to clarify the "only function bodies count" better: every character in the code counts, except for the overhead required to declare and define the functions and the libraries required to do basic I/O. By basic I/O I still mean no language features which directly deal with complex numbers. The main or equivalent where you call these functions don't count but you are not allowed to do anything besides using those functions for demonstrative purpose.

  • 1
    \$\begingroup\$ any bonus for operator overload (in languages that support it)? \$\endgroup\$ Oct 14, 2012 at 11:29
  • \$\begingroup\$ You're obviously talking about languages that use the word "function" in the way C does, like Python, Lisp, JavaScript etc.. But read and print aren't actually functions (they have side-effects), so in a more rigorous language you can't define them in that precise way. Are those languages "out", or may we use the corresponding signatures (e.g. read :: IO ComplexNum and print :: ComplexNum -> IO() in Haskell)? Or why shall we not rather define functions to parse / build strings, rather than perform actual IO? \$\endgroup\$ Oct 14, 2012 at 15:05
  • \$\begingroup\$ If only the function bodies count, are any lines of e.g. standard library includes for free, or permitted at all? \$\endgroup\$ Oct 14, 2012 at 15:10
  • \$\begingroup\$ @leftaroundabout: includes are free, unless they deal with complex numbers, in which case they are not permitted. The point is, you have to do all the handling of complex numbers by yourself. \$\endgroup\$
    – vsz
    Oct 14, 2012 at 15:19
  • \$\begingroup\$ Allright. But I suppose any other code outside the function bodies is forbidden? In most languages it would be natural to first properly declare the type (class, or whatever) of the complex numbers, but it's easy to do this in such a way that the actual functions become trivial. — Are you going to answer my first comment, yet? \$\endgroup\$ Oct 14, 2012 at 16:03

5 Answers 5


APL (33 + 16 + 1 + 1 + 14 + 17 = 82)

APL does have support for complex numbers if you use it (of the format 5J6, like Python's 5+6j), but it is of course not used.

I represent complex numbers as a 2-tuple of regular numbers, (A B) where A is the real part and B is the imaginary part. This means I can use APL's + and - operators directly, as they can be used on multidimensional types. (i.e. 1+2 3 4 gives 3 4 5 and 1 2+20 10 gives 21 12).

An APL function is represented as {body}. Functions are first-class objects. I have counted the function body without the braces, except for + and - which I've counted as 1 each.

read  ← {⎕ML←3⋄(1,1-2×'-'∊⍵)×⍎¨⍵⊂⍨⍵∊'.',⎕D} ⍝ 33 chars
print ← {⍕(⊃⍵)'+'(⊃⌽⍵)'i'}                   ⍝ 16 chars
add   ← +                                      ⍝ 1 char
sub   ← -                                      ⍝ 1 char
mul   ← {(-/⍺×⍵),+/⍺×⌽⍵}                      ⍝ 14 chars
div   ← {⍺mul 1 ¯1×⍵÷+/⍵*2}                   ⍝ 17 chars

Usage: (clarification: APL is evaluated right-to-left so this is actually calculating 8+9i ÷ 5+6i.)

      print (read⍞) div (read⍞)
5 + 6i
8 + 9i
1.540983607 + ¯0.04918032787 i
  • \$\begingroup\$ print←{∊⍵,¨'+i'} \$\endgroup\$
    – Adám
    Oct 26, 2016 at 19:06
  • \$\begingroup\$ read←{⍎¨w⊂⍨'-+'∊⍨w←'+',⍵~' i'} \$\endgroup\$
    – Adám
    Oct 26, 2016 at 19:10

D (205 chars)

import stdio;

struct Complex{
  real a,b;

  this(real a,real b){

  static Complex read(){
      Complex c;
      return c;

  /** does both addition and substraction */
  Complex opOpBinary(op)(Complex o)if(op=="+"||op=="-"){
    mixin("return Complex(a"~op~"o.a,b"~op~"o.b);");

  Complex opBinary(op)(Complex o)if(op=="*"){
    return Complex(a*o.a-b*o.b,a*o.b+b*o.a);

  Complex opBinary(op)(Complex o)if(op=="/"){
    real z=c**2+d**2
    return this*Complex(o.a/z,-o.b/z);

  void write(){


using operator overloading

I didn't count the constructor

  • 1
    \$\begingroup\$ +1 for showcasing some of the most hideous syntax I've ever seen in any language. \$\endgroup\$ Oct 14, 2012 at 21:42

Python, 131 chars

add=lambda (a,b),(c,d):(a+c,b+d)
sub=lambda (a,b),(c,d):(a-c,b-d)
mul=lambda (a,b),(c,d):(a*c-b*d,a*d+b*c)
def div(x,(c,d)):z=c**2+d**2;return mul(x,(c/z,-d/z))
def _print(x):print"%f+%fi"%x


Makes lots of use of lambda unpacking, which I'm not including in my "body" count. (I'm counting everything after the first :). Kinda cheating, but I'm not really sure how to count it otherwise.

  • \$\begingroup\$ Doesn't work with e.g. 1 - 3i this way. \$\endgroup\$ Oct 14, 2012 at 18:37
  • \$\begingroup\$ @leftaroundabout: true. The input format hasn't really been well-specified (e.g. is 3 passed as 3 or 3+0i?). \$\endgroup\$ Oct 14, 2012 at 18:46

C# – 369 (I guess)

Func<float[]>read=()=>{var m=new Regex(@"(\d*(\.\d*)?) *([+-]) *(\d*(\.\d*)?)i").Match(Console.ReadLine()).Groups;return C(float.Parse(m[1].Value),float.Parse(m[2].Value+m[4].Value));};
Action<float[]>print=x=>{Console.WriteLine("{0} {1} {2}i",x[0],x[1]>=0?"+":"-",Math.Abs(x[1]));};

var a = read();
var b = read();
var c = C(3, -7);
var d = C(2, 5);
var e = div(a,c);
var f = mul(b,d);
var g = add(e,f);

Not sure about the character counting definition, really…


Haskell 698

Counted everything before main. This question struck me as being too straight forward, so I did everything in my power to make my answer more interesting. Also Haskell borks if you redefine Prelude functions (div, print, read), so I renamed those.

import Control.Arrow 
import Control.Monad
import Control.Applicative
import Data.List.Split
f%b=a$j f b
mul=curry m
b`d1v`c=b`mul`(j (/uncurry(+)(j(^2)c)).second negate$c)
s :: (Show a) => (a, a) -> String
s=uncurry(++).first(++" ").second((++"i").(let g('-':x)="- "++x;g x="+ "++x in g)).j show
pr1nt :: (Show a) => (a, a) -> IO ()
t=filter(`notElem`" i")
re4d :: (Read a, Num a) => String -> (a, a)
re4d s|elem '+'s=(\[x,y]->j(read.t)(x,y)).splitOn"+"$s

main= do
  let p = pr1nt
  a <- fmap re4d getLine
  b <- fmap re4d getLine
  p $ a `add` b
  p $ a `sub` b
  p $ a `mul` b
  p $ a `d1v` b

This spits a "non-exhaustive pattern-match in input" if the input given does not match "a (+|-) bi".

  • \$\begingroup\$ I'm fairly certain that you could do import Prelude hiding (div,print,read) as long as you don't plan on ever using those functions. If you do need them you can probably import them qualified. \$\endgroup\$
    – Matt
    Oct 15, 2012 at 17:48
  • \$\begingroup\$ I know that's possible, I just didn't want to sacrifice char count :P. \$\endgroup\$
    – walpen
    Oct 15, 2012 at 21:31

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.