Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I always used a Mandelbrot image as the 'graphical' version of Hello World in any graphical application I got my hands on. Now it's your guys' turn.

  • Language must be capable of graphical output or drawing charts (saving files disallowed)
  • Render a square image or graph. The size at least 128 and at most 640 across*
  • The fractal coordinates range from approximately -2-2i to 2+2i
  • The pixels outside of the Mandelbrot set should be colored according to the number of iterations before the magnitude exceeds 2 (excluding* black & white)
  • Each iteration count must have a unique color*, and neighboring colors should preferably be easily distinguishable by the eye
  • The other pixels (presumably inside the Mandelbrot set) must be colored either black or white
  • At least 99 iterations
  • ASCII art not allowed

*) unless limited by the platform, e.g. graphical calculator

(shrunken images)

Winning conditions:
Shortest version (size in bytes) for each language will get a mention in this post, ordered by size.
No answer will ever be 'accepted' with the button.

Current ranking (2014-05-30 06:59 GMT):

share|improve this question
"Easily distinguished by the eye" is hard to make objective. ...Also, apart from your personal association of the two, the Mandelbrot set has nothing to do with Hello World, so it's best to omit that from the title unless you are deliberately trolling the search engines. – Jonathan Van Matre Mar 7 '14 at 21:50
Related: ASCII Mandelbrot (although some of the answers posted there aren't ASCII and could probably fit better as answers to this question). – Peter Taylor Mar 7 '14 at 22:44
I've seen a few people now mentioning that they render the Mandelbrot as a "Hello World". I've done that too, for something like 30 years. The Mandelbrot is the perfect "Hello World" because it shows both that you have pixel access to the display and gives a good feel for compute bound performance on the new platform. – Roger Dahl Mar 9 '14 at 2:00
Great idea to ask a question which requires a combination of mathematical and aesthetic sensitivities, then impose all the the design decisions in advance. – jwg Mar 10 '14 at 8:25
Anyone manages to make one in brainfuck WINS, I'd say :D – MadTux Mar 10 '14 at 18:45

28 Answers 28

Sharp EL-9300 Graphics Calculator, 296 bytes

This was my secondary school graphing calculator, getting on for 20 years ago! I remember writing a mandelbrot generator for it way back then. And sure enough, its still sitting there in the NV memory:

Range -2.35,2.35,.5,-1.55,1.55,0.5
Label ly
Label lx
Label ln
If zx²+zy²>4Goto esc
If n<20Goto ln
Label esc
If fpart (n/2)=0Goto npl
Plot x,y
Label npl
If x<=2.35Goto lx
If y<=1.55Goto ly

It took about 90 minutes to render.

This is totally ungolfed. I'm sure I could save a bit of space, but I just wanted to share this historical curiosity!

I love that the only control statements available are gotos.

Here's a photo. I don't have any other means to get the graphical output out: enter image description here

share|improve this answer
Me too, but my NV memory went blank after years of shelf-time. – Mark Jeronimus Mar 8 '14 at 9:10
zx²+zy²>4 couldn't that be Abs(x)>2? – Mark Jeronimus Mar 8 '14 at 9:31
Interesting. So you've been a nerd for quite a while. – devnull Mar 9 '14 at 3:34
Nice "Screenshot" – meawoppl Mar 9 '14 at 10:01
@alexy13 OP made an exception for languages that had monochrome output and mentioned calculators as an example. – Sylwester Mar 9 '14 at 18:08

I came across this the other day. I don't take credit for it, but damn, is it awesome:


_                                      =   (
                               V       ,B,c
                             :c   and Y(V*V+B,B,  c
               (              2+c-4*abs(V)**-0.4)/i
                 )  ;v,      x=1500,1000;C=range(v*x
                  );import  struct;P=struct.pack;M,\
            j  ='<QIIHHHH',open('M.bmp','wb').write
for X in j('BM'+P(M,v*x*3+26,26,12,v,x,1,24))or C:
            i  ,Y=_;j(P('BBB',*(lambda T:(T*80+T**9
                  *i-950*T  **99,T*70-880*T**18+701*
                 T  **9     ,T*i**(1-T**45*2)))(sum(
               [              Y(0,(A%3/3.+X%v+(X/v+
                             /x   -2.7,i)**2 for  \
                               A       in C
                                       )   )

enter image description here

share|improve this answer
Seems to be disallowed: the regions are not easily distinguishable, or even at all. – primo Mar 8 '14 at 13:32
disallowed or not, this is pretty awesome :D – Navin Mar 9 '14 at 2:28
+1 for the most beautiful output – Digital Trauma Mar 9 '14 at 4:05
@DigitalTrauma, heck, +1 for most beautiful input! – Brian S Mar 10 '14 at 15:26
Does this count as a quine? ;-) – Blazemonger Mar 10 '14 at 21:04

LaTeX, 673 bytes


Result 129x129 (129 × 129)

The PDF image consists of colored square units with size 1bp × 1bp.


% count register \size contains the width and height of the square
\usepackage[margin=0pt,papersize=\size bp]{geometry}
% \Loop: for (#1 = 0; #1 < #2; #1++) {#3}
  \advance\d23 \ifnum\d>\iterations\advance\d-\iterations\fi
% \c: row
% \d: column
% \e: iteration
  \typeout{c: \the\c}%
         % calculate z(n+1) = z^2(n) + k
         % calculate abs(z)^2
         \ifdim\temp pt>4pt\csname\the\e\endcsname\e\iterations\fi
share|improve this answer

x86 DOS Assembly - 208 177 173

The full binary, in HEX, that I created by hand, is:


The sample image is:

Mandlebrot screen shot with black cropped

The full source in readable ASM is fairly long (I used this to figure out how I was coding this sucker):

ASSUME CS:code, DS:code
ORG 0100h

; *****************************************************************************
  ; Mandlebrot coordinates
  zr   = DWORD PTR [SI+0]
  zi   = DWORD PTR [SI+4]
  cr   = DWORD PTR [SI+8]
  ci   = DWORD PTR [SI+12]
  zrsq = DWORD PTR [SI+16]
  zisq = DWORD PTR [SI+20]

  ; Temp int
  Temp = WORD PTR  [SI+28]

  ; ===========================================================================
  ; Initialize

  ; Initialize the FPU

  ; SI points to our memory
  mov si, 0A000h ; So we can push it

  ; Shave off some bytes by reusing 100
  mov dx, 100

  ; Switch to MCGA
  mov ax, 013h
  int 010h

  ; ES:DI is the end of our drawing area
  push si
  pop es
  mov di, 63879
  std ; We're using stosb backwards

  ; Initialize our X and Y
  mov bp, 199
  mov cx, bp

  ; ===========================================================================
  ; Main draw loop

  ; Get our next mandelbrot value
  call GMV

  ; Store it
  mov al, bl

  ; Decrement our X
  dec cx
  jns MainLoop

  ; Decrement our Y
  mov cx, 199
  sub di, 120
  dec bp
  jns MainLoop

  ; ===========================================================================
  ; Done

  ; Wait for a key press
  xor ax, ax
  int 016h

  ; Change back to text mode
  mov ax, 3
  int 010h

  ; Exit to DOS
  int 020h

; *****************************************************************************
; GMV: Get Mandelbrot Value
; Gets the value for the next Mandelbrot pixel
; Returns:
;   BL - The color to use
  ; ===========================================================================
  ; Initialize

  ; cr = (x - 100) / 50;
  mov ax, cx
  sub ax, dx                  ; \
  mov Temp, ax                ;  > ST0 = Current X - 100
  FILD Temp                   ; /
  FILD Divisor                ; ST0 = 50, ST1 = Current X - 100
  FDIVP                       ; ST0 = (Current X - 100) / 50
  FSTP cr                     ; Store the result in cr

  ; ci = (y - 100) / 50;
  mov ax, bp
  sub ax, dx                  ; \
  mov Temp, ax                ;  > ST0 = Current Y - 100
  FILD Temp                   ; /
  FILD Divisor                ; ST0 = 50, ST1 = Current Y - 100
  FDIVP                       ; ST0 = (Current Y - 100) / 50
  FSTP ci                     ; Store the result in ci

  ; zr = zi = zrsq = zisq = 0;
  FST zr
  FST zi
  FST zrsq
  FSTP zisq

  ; numiteration = 1;
  mov bl, 1

  ; ===========================================================================
  ; Our main loop

  ; do {

  ; zi = 2 * zr * zi + ci;
  FLD zr
  FMUL zi
  FIMUL TwoValue
  FADD ci
  FST zi ; Reusing this later

  ; zr = zrsq - zisq + cr;
  FLD zrsq
  FSUB zisq
  FADD cr
  FST zr ; Reusing this since it already is zr

  ; zrsq = zr * zr;
  ;FLD zr ; Reused from above
  FMUL zr
  FSTP zrsq

  ; zisq = zi * zi;
  ;FLD zi ; Reused from above
  FMUL zi
  FST zisq ; Reusing this for our comparison

  ; if ((zrsq + zisq) < 4)
  ;   return numiteration;
  FADD zrsq
  FILD FourValue
  FSTSW ax
  jb GMVDone

  ;} while (numiteration++ < 200);
  inc bx
  cmp bl, dl
  jb GMVLoop

  ;return 0;
  xor bl, bl


; *****************************************************************************
; Data

; Divisor
Divisor DW 50
; Two Value
TwoValue DW 2
; 4 Value
FourValue DW 4

END start

This is designed for compiling with TASM, runs in MCGA, and waits for a keypress before ending the program. The colors are just the default MCGA palette.

EDIT: Optimized it, now it draws backwards (same image though), and saved 31 bytes!

EDIT 2: To assuage the OP, I have recreated the binary by hand. By doing so, I also shaved another 4 bytes off. I documented every single step of the process, showing all of my work so anybody can follow along if they really want to, here (warning, it's boring and very long):

I used a couple regex's in EditPadPro, to find all the ; Final: ... entries in the file and dump them as hex binary to a .com file. The resulting binary is what you see at the top of this post.

share|improve this answer
Machine-code doesn't count. If that counts, then any language producing byte-code or machine-code should be shorter. I count 820 after changing everything to 1-character long names. – Mark Jeronimus Mar 10 '14 at 6:32
No. I can hand convert ASM to binary if really necessary. It will come out with the exact same 177 bytes that my assembler helped with. The resulting code can be pasted by anybody with a binary editor into a new file, saved out, 177 bytes, and it will work as expected. Apparently SO is divided on ASM submissions, so maybe you should clarify if you feel it does not count:… – Mark Ormston Mar 10 '14 at 19:14
I can translate Basic code to assembly code if I take the time. That doesn't make it a valid submission. Read the comment on the first post of the page you linked. I'm with @AShelly. I quote: "You should be scored on the language you write in, not your compiler's output. (Unless you really are writing in raw binary...)" – Mark Jeronimus Mar 11 '14 at 18:42
Alright, so, to prove this a valid entry, I spent the time it took to hand translate this to binary. I have updated my answer accordingly. – Mark Ormston Mar 12 '14 at 5:34
The thing is, there is no compiler with assembly. You just use macros. Saying that it doesn't count is like saying you can't use any predefined #define statements in C. It's just time consuming to manually replace it all. – Mark Ormston Mar 12 '14 at 16:33

Java - 505 405 324

Just a standard calculation, with golfitude now with extra golfitude.

enter image description here


import java.awt.*;class M{public static void main(String[]v){new Frame(){public void paint(Graphics g){for(int t,s,n=640,i=n*n;--i>0;g.setColor(new Color(s*820)),g.drawLine(i/n,i%n+28,i/n,i%n),setSize(n,668)){float c=4f/n,a=c*i/n-2,b=i%n*c-2,r=a,e=b,p;for(s=t=99;t-->0&&r*r+e*e<4;s=t,p=r*r-e*e+a,e=r*e*2+b,r=p);}}}.show();}}

With line breaks:

import java.awt.*;
class M{
    public static void main(String[]v){
        new Frame(){
            public void paint(Graphics g){
                for(int t,s,n=640,i=n*n;--i>0;g.setColor(new Color(s*820)),g.drawLine(i/n,i%n+28,i/n,i%n),setSize(n,668)){
                    float c=4f/n,a=c*i/n-2,b=i%n*c-2,r=a,e=b,p;
share|improve this answer
f.setSize(n,668); - depends heavily on the used Theme, but I'll accept it. – Mark Jeronimus Mar 8 '14 at 9:11
You can drop the imports in Java because they're auto-generated anyway. – Mark Jeronimus Mar 8 '14 at 9:23
I also see double where float could be used if you tried – Mark Jeronimus Mar 8 '14 at 9:29
JFrame => Frame shaves off 2 chars. Although you can't close the window anymore. ;) – EthanB Mar 8 '14 at 15:01
Your class do not need to be public. Further, use Java 8 to get rid of the final modifier. And you must not omit the imports in order to be a complete submission. – Victor Stafusa Mar 10 '14 at 4:53

Javascript (ECMAScript 6) - 315 Characters


Default Output

JSFIDDLE - Requires Firefox (as the only browser to have, so far, implemented ECMAScript 6 arrow functions)

  • Change n to vary the image size (and number of iterations).
  • Change the values passed in the f(87);f(0);f(0); calls (near the end) to change the RGB colour values. (f(8);f(8);f(8); is greyscale.)

With f(8);f(23);f(87);:

enter image description here

share|improve this answer
Nice. d=document would save you a few more. (Also, Is there a reason for creating the canvas? Does codegolf assume a certain level of HTML available?) – Matthew Wilcoxson Mar 10 '14 at 15:47

Python w/ PIL - 166 bytes

import Image
for x in range(d*d):

Output (will open in the default *.bmp viewer):

share|improve this answer
You can shave off 3 if you get rid of the y loop. r=range(d*d), use x/d and x%d for x and y. – Geobits Mar 8 '14 at 16:15
@Geobits the idea actually saved 10, thanks! – primo Mar 8 '14 at 16:28
Complex types can be initialized like: c=1+2j, which I think would save you a couple characters with: z=o=x/9e4-2+(x%d/150.-2)*1j;c=99 – meawoppl Mar 9 '14 at 3:10
@meawoppl another 7 :D – primo Mar 9 '14 at 5:07
Technically disallowed: this doesn't any graphical output feature of Python itself (and implicitly saves a temporary file). – nneonneo Mar 9 '14 at 5:51

J, 73

(0,?$~99 3)viewmat+/2<|(j./~i:2j479)(+*:) ::(3:)"0^:(i.99)0

mandelbrot set

Edit, some explaining:

x (+*:) y           NB. is x + (y^2)
x (+*:) ::(3:) y    NB. returns 3 when (+*:) fails (NaNs)
j./~i:2j479         NB. a 480x480 table of complex numbers in required range
v =: (j./~i:2j479)(+*:) ::(3:)"0 ]     NB. (rewrite the above as one verb)
v z0                NB. one iteration of the mandelbrot operation (z0 = 0)
v v z0              NB. one iteration on top of the other
(v^:n) z0           NB. the result of the mandelbrot operation, after n iterations
i.99                NB. 0 1 2 3 4 ... 98
(v^:(i.99))0        NB. returns 99 tables, one for each number of iterations
2<| y               NB. returns 1 if 2 < norm(y), 0 otherwise
2<| (v^:(i.99))0    NB. 99 tables of 1s and 0s
+/...               NB. add the tables together, element by element.
NB. we now have one 480x480 table, representing how many times each element exceeded norm-2.
colors viewmat M    NB. draw table 'M' using 'colors'; 'colors' are rgb triplets for each level of 'M'.
$~99 3              NB. 99 triplets of the numbers 99,3
?$~99 3             NB. 99 random triplets in the range 0 - 98 and 0 - 2
0,?$~99 3           NB. prepend the triplet (0,0,0): black
share|improve this answer
+1 but would it be possible for you to explain a little how that code work? In particular i m curious to know how (where in the code) does it pick the colors? – plannapus Mar 10 '14 at 8:40
@MarkJeronimus, I can make it 70 but I kept some things for clarity. I, thus, took the liberty to ignore the LF when counting. – Eelvex Mar 10 '14 at 12:39
@plannapus, OK, added some comments. The color picking is done with (0,?$~99 3) which produces 100 rgb triplets, one for each level. Because of the randomness, you might get less than 100 triplets so some levels will have a smoother transition (but still have different colors). – Eelvex Mar 10 '14 at 13:07
@Eelvex Thanks! – plannapus Mar 10 '14 at 13:09

Mathematica 214 191 215

Back to Black

My earlier submission did not meet the requirement to leave the inside all black (or white). This does.

ArrayPlot[Table[m[a+I b],{b,-2,2,.01},{a,-2,2,.01}],DataRange→{{-2,2},{-2,2}},


share|improve this answer
{b, -2, 2, .01}, {a, -2, 2, .01} is shorter and closer to the rules – Mark Jeronimus Mar 7 '14 at 23:50
@MarkJeronimus Thanks. I used the suggested range for the iterating picture. – DavidC Mar 8 '14 at 3:20
You had it almost right, then you made the inside non-black. The last frame in the GIF is black inside and an allowed answer. EDIT: and I count 195 bytes. – Mark Jeronimus Mar 8 '14 at 9:20
I missed the point about being black. The count increased because some single characters became two characters in the cut-and-paste to SE. – DavidC Mar 8 '14 at 13:34

Python with Pylab+Numpy 151 Bytes

I couldn't bear to see a non-DQ'ed Python entry, but I think I really outdid myself on this one, and I made it down to 153 characters!

import numpy as n
from pylab import*
while i:x[(abs(r)>2)&(x==0)]=i;r=r*r+c;i-=1

Also, notably, the second to last line raises 4 distinct runtime warnings, a new personal record!

enter image description here

share|improve this answer
I count 152. No space is required between import and *, and not defining f at all should be shorter, unless i've misunderstood something, which is possible. You should also change it around such that 0 iterations and 1 iterations are distiguished (they're currently both grey). – primo Mar 9 '14 at 14:02
Weird. Does wc include the eof? Fixed and slightly smaller. Just a moment. – meawoppl Mar 9 '14 at 17:46
I get 151 with wc. First golf, so not sure how to score it. – meawoppl Mar 9 '14 at 18:01
I count 150, without trailing newline. Some interpreters/compilers demand one, but the python interpreter does fine without. Not sure about wc, but maybe try stat -c %s instead. Are the black upper and lower borders part of the image? – primo Mar 9 '14 at 18:09
150 here too. Besides, you sure it's 640 or less wide, and not 999? The image looks antialiased – Mark Jeronimus Mar 10 '14 at 6:35

C + Allegro 4.2.2 - 248 bytes

x=-1,y,K=400;float a,h,c,d,k;main(i){set_gfx_mode('SAFE',K,K,allegro_init(),0);while(x++<K)


MSet 1

share|improve this answer
You should mention that this is Allegro 4 (which is quite different from Allegro 5). Which exact version is this? – Victor Stafusa Mar 10 '14 at 4:57
it's either 246 or 249 long – Mark Jeronimus Mar 10 '14 at 6:42
@Victor Allegro 4.2.2. – Oberon Mar 10 '14 at 14:34
@MarkJeronimus Notepad++ tells me it's 248 characters long. – Oberon Mar 10 '14 at 15:33
Notepad++ is wrong. – Mark Jeronimus Mar 10 '14 at 19:27

BBC Basic (228 bytes)

What about languages that nobody ever heard of in code golf? Most likely could be optimized, but I'm not quite where - improvements possible. Based of, but I tried to code golf it as much as possible.

IFx*x+y*y>4EXIT FOR

The generated Mandelbrot set

The > symbol on image is prompt, and it's automatically generated after running the program.

share|improve this answer
No need to plot twice, just go with a more inefficient version. Doesn;t it support NEXT Y,X? – Mark Jeronimus Mar 9 '14 at 11:59

Mathematica 10.0 on Raspberry Pi, 19 chars


MandelbrotSetPlot is a new function in Mathematica 10.0.

enter image description here

share|improve this answer
How convenient, that this built in function just happens to satisfy all my requirements (except location, which can be set with 13 more characters). Except this is a standard loophole. – Mark Jeronimus Mar 30 '14 at 10:03
Code golf is generally won by specialist languages with single-character tokens, or by systems like Mathematica that have a massive number of special functions built-in. To use them is not cheating, any more than using single-character commands would be in APL. – Michael Stern Apr 17 '14 at 15:08

R, 199 211 characters

Old solution at 199 characters:

r=seq(-2,2,l=500);c=t(sapply(r,function(x)x+1i*r));d=z=array(0,dim(c));a=1:25e4;for(i in 1:99){z[a]=c[a]+z[a]^2;s=abs(z[a])<=2;d[a[!s]]=i;a=a[s]};image(d,b=0:99,c=c(1,sample(rainbow(98))),ax=F,asp=1)

With indentation:

c=t(sapply(r,function(x)x+1i*r)) #Produces the initial imaginary number matrix
d=z=array(0,dim(c)) #empty matrices of same size as c 
a=1:25e4            #(z will store the magnitude, d the number of iterations before it reaches 2)
for(i in 1:99){     #99 iterations
image(d,b=0:99,c=c(1,sample(rainbow(98))),ax=F,asp=1) #Colors are randomly ordered (except for value 0)

enter image description here

Edit: Solution at 211 characters that colors the inside of the set and the outside of the first layer differently:

r=seq(-2,2,l=500);c=t(sapply(r,function(x)x+1i*r));d=z=array(0,dim(c));a=1:25e4;for(i in 1:99){z[a]=c[a]+z[a]^2;s=abs(z[a])<=2;d[a[!s]]=i;a=a[s]};d[a[s]]=-1;image(d,b=-1:99,c=c(1:0,sample(rainbow(98))),ax=F,asp=1)

With indentation:

for(i in 1:99){
d[a[s]]=-1 #Gives the inside of the set the value -1 to differenciate it from value 0.

enter image description here

share|improve this answer
technically black on the outside is disallowed. Did you miss that or is it difficult to implement? – Mark Jeronimus Mar 8 '14 at 9:19
@MarkJeronimus both actually :) I'll try to have a look of how to do that but i m not 100% confident that I ll find a way to do that cleanly. – plannapus Mar 8 '14 at 9:20
@MarkJeronimus Done! – plannapus Mar 8 '14 at 9:40
Second place in the hideous colors division. – meawoppl Mar 9 '14 at 10:02
@meawoppl blame rainbow() :) – plannapus Mar 10 '14 at 7:23

APL, 194 chars/bytes*

'F'⎕WC'Form'('Coord' 'Pixel')('Size'(s s))
'F.I'⎕WC'Image'(0 0)('Picture' 'B')

This is for Dyalog APL with ⎕IO ⎕ML←1 3

Most of the space is taken by API calls to show a bitmap in a window (lines 2, 3, 4)
If there was a shortcut to do it, the code would be down to 60 chars (line 1)


Ungolfed version (only line 1)

s←640            ⍝ size of the bitmap
v←(4×(⍳s)÷s)-2   ⍝ vector of s reals, uniform between ¯2 and 2
m←(0j1×v)∘.+v    ⍝ square matrix of complex numbers from ¯2j¯2 to 2j2
m←{              ⍝ transform each number in matrix m according to the following
  1{             ⍝   function that takes iteration counter as ⍺ and current value as ⍵
    ⍺=99: 0      ⍝     if we have done 99 iterations, return 0
    2<|⍵: ⍺      ⍝     if |⍵| > 2 return the number of iterations done
    (⍺+1)∇c+⍵*2  ⍝     otherwise, increment the iterations and recurse with the new value
  }c←⍵           ⍝   save the initial value as c


(Freeware version run in OS X under Wine. Yes I'm cheap like that.)


*: Dyalog has its own single byte charset, with the APL symbols mapped to the upper 128 byte values, so the entire code can be stored in 194 bytes. Every statement in this footnote is possibly true. Keep calm and carry on golfing.

share|improve this answer

Java - Processing (271 bytes)

void setup(){int h=100,e=5*h,i;float d,v,w,a,b,c;size(e,e);colorMode(HSB,h);loadPixels();d=4./e;v=2;for(int x=1;x<=e;x++){v-=d;w=2;for(int y=0;y<e;){w-=d;a=b=c=0;i=-1;while(a*a+b*b<4&&++i<h){c=a*a-b*b+v;b=2*a*b+w;a=c;}pixels[e*++y-x]=color(i*9%h,h,h-i);}}updatePixels();}


void setup(){
  int h=100, e=5*h, i; //init of size "e", max hue "h", iterator "i"
  float d,v,w,a,b,c; //init of stepwidth "d", y-coord "v", x-coord "w", Re(z) "a", Im(z) "b", temp_a "c"
  d = 4./e;
  v = 2;
  for(int x = 1; x <= e; x++){
    v -= d;
    w = 2;
    for(int y = 0; y < e;){
      w -= d;
      a = b = c = 0;
      i = -1;
      while(a*a + b*b < 4 && ++i < h){
        c = a*a - b*b + v;
        b = 2*a*b + w;
        a = c;
      pixels[e * ++y - x] = color(i*9 % h, h, h-i);

share|improve this answer

GLSL - 225 bytes:

void main(){vec2 c=gl_FragCoord.xy/iResolution.y*4.-2.,z=c,v;for(int i=0;i<99;i++){z=vec2(z.x*z.x-z.y*z.y,2.*z.x*z.y)+c;if(length(z)>2.&&v.y<1.)v=vec2(float(i)/99.,1.);}gl_FragColor=(v.y<1.)?vec4(v,v):texture2D(iChannel0,v);}

Defining variables in the code (242 bytes):

uniform vec3 r;uniform sampler2D t;void main(){vec2 c=gl_FragCoord.xy/r.y*4.-2.,z=c,v;for(int i=0;i<99;i++){z=vec2(z.x*z.x-z.y*z.y,2.*z.x*z.y)+c;if(length(z)>2.&&v.y<1.)v=vec2(float(i)/99.,1.);}gl_FragColor=(v.y<1.)?vec4(v,v):texture2D(t,v);}

See it in ShaderToy

Mandelbrot Golf

This requires a suitable palette texture be loaded as iChannel0. (The colouring here is from the "random pixel" texture on ShaderToy).

share|improve this answer
Variable declarations should be counted too, unless they can be auto-generated from the code. (color scheme is fine if it's only available as an external setting) – Mark Jeronimus Mar 10 '14 at 6:40
@MarkJeronimus: For the ShaderToy environment, these variables are fixed. Otherwise, for standard shaders, I would have picked shorter variable names. – nneonneo Mar 10 '14 at 7:25
Is this the fastest of them all? – Demetri Aug 3 '15 at 7:15

Matlab (89 bytes)

for j=1:99,Z=Z.*Z+C;K=K+(abs(Z)<2);end,imagesc(K)

Output -

enter image description here

Doesn't satisfy the requirement that the inner cells must be black or white, but that can be satisfied by either (1) using imshow(K) instead of imagesc(K) (requires 1 fewer byte but needs the image processing toolbox) or (2) appending colormap hot (requires 12 more bytes).

Ungolfed version -

Z = zeros(N);
K = Z;

C = X+1i*Y;

for j = 1:99
  Z = Z.*Z + C;
  K(K==0 & abs(Z) > 2) = j;

share|improve this answer
Using a library is fine if it's packaged in Matlab by default and any user can guess it's being used from the code or the error messages. – Mark Jeronimus Mar 10 '14 at 19:19
Nice, you beat me. I like the C-C in place of my 0*e(401). Plus, you're not using N. And we can get a little shorter using my m+=abs(z)<2 idea in place of your K(~K&abs(Z)>2)=j. – aschepler Mar 11 '14 at 12:33
The default colormap jet and colormap hot are both incorrect though - they only have 64 distinct colors. colormap(hot(101)) doesn't look visually distinguishable to me. colormap([0,0,0;jet(100)]) is maybe acceptable but iffy. – aschepler Mar 11 '14 at 12:39
Does that work? On Octave, K=K+abs(Z)<2 means K=((K+abs(Z))<2). (So I was wrong about the one byte estimate to eliminate +=.) – aschepler Mar 11 '14 at 13:06
Ah, good point! Edited. – Chris Taylor Mar 11 '14 at 13:28

Octave (212 136 bytes)

(Now including some ideas due to @ChrisTaylor.)

[y,x]=ndgrid(-2:.01:2);z=c=x+i*y;m=c-c;for n=0:99;m+=abs(z)<2;z=z.^2+c;end;imagesc(m);colormap([hsv(128)(1+mod(0:79:7890,128),:);0,0,0])

With whitespace:

[y,x] = ndgrid(-2:.01:2);
z = c = x + i*y;
m = c-c;
for n=0:99
    m += abs(z)<2;
    z = z.^2 + c;


Mandelbrot steps to abs(z)>2

To convert to Matlab, change "m+=abs(z)<2" to "m=m+(abs(z)<2)". [+3 bytes]

To make the aspect ratio 1:1, add ";axis image". [+11 bytes]

My first answer (212 bytes):

[x,y]=meshgrid(-2:.01:2);z=c=x+i*y;m=0*e(401);for n=0:99;m+=abs(z)<2;z=z.^2+c;endfor;t=[0*e(1,7);2.^[6:-1:0]];[s{1:7}]=ndgrid(num2cell(t,1){:});t=1+sum(cat(8,s{:}),8);imagesc(m);colormap([hsv(128)(t(:),:);0,0,0])
share|improve this answer
There's probably a shorter way to get a discontinuous colormap.... – aschepler Mar 8 '14 at 20:40
Yes, much better now. – aschepler Mar 9 '14 at 1:13
+1 nice and concise solution. But your aspect ratio is not 1:1 (cf. rule n°2: output should be square). – plannapus Mar 10 '14 at 7:39
Fixing the aspect ratio will take 11 more bytes: append ";axis image". Is that required to qualify? – aschepler Mar 10 '14 at 14:39
i think it was just me nitpicking :) , the OP doesn't seem to have a problem with it since he didn't say anything. – plannapus Mar 11 '14 at 7:46

JavaScript + HTML5 (356B)

(Note: lines ending with '//' are added here for some readability)

Performant version (375B):

<body onload='var
w,h=w=C.width=C.height=500,X=C.getContext("2d"),I=X.createImageData(w,h),, //
y=0,f=255,T=setInterval(function(x,i,j,k,l,c,o){for(x=0;x<w;){                     //
++y-h||clearInterval(T)},0)'><canvas id=C>

Slow version (356B): remove the 'var' and parameters in the inner function so that the global scope is used.

Try it out:

enter image description here

share|improve this answer
Forgive me if I don't understand your instructions on making the short version. – Mark Jeronimus Mar 8 '14 at 21:33
No problem. Remove var w, at the beginning, and change function(x,i,j,k,l,c,o) to function(). – ɲeuroburɳ Mar 8 '14 at 21:35

gnuplot 110 (105 without newlines)

Obligatory gnuplot entry. It's been done countless times but this one is from scratch (not that it's difficult). I like how gnuplot golfs its commands intrinsically :)

se vi map
se si sq
se isos 256
sp [-2:2] [-2:2] f(0,x+y*{0,1},99) w pm


set view map
set size square
set isosamples 256
splot [-2:2] [-2:2] f(0,x*{1,0}+y*{0,1},99) with pm3d

However, I'm DEEPLY disappointed at the entry of complex numbers. x*{1,0}+y*{0,1} must be the saddest existing way of constructing a complex number.

Oops, the image: gnuplot mandelbrot

Set isosamples higher for better resolution. We could also say unset tics and unset colorbox for a pure image, but I think this version qualifies just fine.

share|improve this answer
Bet it's copy/pasta from the first google hit "gnuplot mandel". For starters, *{1,0} is unity and is more like a code-bowling way of saying *1, and probably can be dropped. (untested) – Mark Jeronimus Mar 10 '14 at 6:26
No it's not a copy-paste. It's a very straight forward formula and it wasn't even necessary to search for it. However, I did find the pages you get with that search when I was looking for a better way of initializing complex numbers (their implementation is different, well, as different as it can be in this case). Thanks for the tip about the real part, it works. Fixing. – orion Mar 10 '14 at 7:53

Floater, 620 pixels

A language I made up when I got inspired by my own challenge, as well as from the esoteric language Piet.

enter image description here

share|improve this answer

Perl 6: 107 characters, 108 bytes (DQ'ed)

.say for <P3 200 200 99>,map
{(+(0,* **2+$^z...*.abs>2)[^100]X*3,21,4)X%100},{@_»i X+@_}(-2,*+.02...^*>=2)

Outputs this 200x200 ppm file (converted to PNG):

Perl 6 Mandelbrot PNG

I recognize that outputting an image file goes against the rules, but I'm posting this here pending a version that is able to draw the image itself.

I originally had the colors a little prettier, and the program a few bytes shorter, but I decided there wasn't enough contrast between layers.


.say for <P3 200 200 99>; # Print the PPM header

# Print the results of looping over [-2-2i,2+2i],
# I.e., all the possible additions (X+)
# of -2 to 2 in 200 parts (-2,*+.02...^*>=2)
# with -2i to 2i in 200 parts (@_»i)
.say for {@_»i X+ @_}(-2, * + .02 ...^ * >= 2).map: {
    # How many iterations it takes to get to 2, up to 100,
    # Manipulated to get an R, G, and B color value
      +(0, * ** 2 + $^z ... *.abs > 2)[^100]
      #  R G  B
      X* 3,21,4
    ) X% 100
share|improve this answer

Windows PowerShell (v4), 299 bytes

Mandelbrot fractal picture

# Linewrapped here for show:

$M='System.Windows.Forms';nal n New-Object;Add-Type -A System.Drawing,$M;(
$a=n "$M.Form").backgroundimage=($b=n Drawing.Bitmap 300,300);0..299|%{
$r=$_;0..299|%{$i=99;$k=$C=n numerics.complex($_/75-2),($r/75-2);while(((

# The single line 299 char entry version:

$M='System.Windows.Forms';nal n New-Object;Add-Type -A System.Drawing,$M;($a=n "$M.Form").backgroundimage=($b=n Drawing.Bitmap 300,300);0..299|%{$r=$_;0..299|%{$i=99;$k=$C=n numerics.complex($_/75-2),($r/75-2);while((($k=$k*$k).Magnitude-lt4)-and$i--){$k+=$C}$b.SetPixel($_,$r,-5e6*++$i)}};$a.Show()


  • Run a normal PowerShell console (ISE might not work)
  • Copy/paste code in, press Enter
  • Wait - it takes a minute or more to run
  • The only way to quit is to close the console


  • There's a tiny bit of rule-testing going on with the colours inside the set; the rules say "The other pixels (presumably inside the Mandelbrot set) must be colored either black or white'"; the code is colouring the pixels completely black RGB(0,0,0) ... it just happens to be a transparent black RGBA(0,0,0,0). So what shows up is the form background colour of the current Windows theme, a slightly off-white RGB(240,240,240) in this case.
share|improve this answer
I'd change lt2 to lt4 to make it a "mandelbrot set" instead of the image you have now, Many points of the set are swallowed up by the color bands. – Mark Jeronimus Sep 30 '15 at 11:05
Apparently Magnitude is a*a+b*b not sqrt(a*a+b*b) – Mark Jeronimus Sep 30 '15 at 13:41
I thought I tested that earlier, but I went in search of an answer to "where's the horizontal line on the left gone?", and after a bit, I found it exactly where you said, -lt4. Which is good - thank you. I've updated my answer with corrected code, and image. (Will have to rethink my understanding of what it's doing, since I'm missing something). – TessellatingHeckler Sep 30 '15 at 18:02

Perl + GD, 264

$I=new GD::Image $s=499,$s;Z(0,0,0);Z(map rand 256,1..3)for
GD;$I->setPixel($x,$y,$c<99&&$c)}}print $I->png

Mandelbrot fractal from Perl+GD

Golfed from this code

share|improve this answer
Nominated: most ugly color scheme. – meawoppl Mar 9 '14 at 9:41

Javascript, 285B

Based off my code and some improvements on MT0's code, I've got this down to 285B in colour:


in action:

was: Coffeescript, 342B

document.body.appendChild V=document.createElement 'Canvas'
P.push "rgba(0,0,0,"+Math.random()*i/N+')' for i in [N..0]
X=V.getContext '2d'
for x in [0..Z]
 for y in [0..Z]
  [a,b]=[a*a-b*b+4*x/Z-3,2*a*b+4*y/Z-2] while a*a+b*b<4 and N>k++
  X.fillRect x,y,1,1

Coffeescript is supposed to be readable :-/ see it in action:

Mandelbrot Coffeescript

share|improve this answer
OP asks for color unless your platform doesn't support color. Looks great, though, and nice concise code. Welcome to PPCG! – Jonathan Van Matre Mar 13 '14 at 16:45

QBasic, QuickBasic, QB64 - 156 153

FOR J=0TO 191
FOR I=0TO 191

Standard DOS palette:

enter image description here

share|improve this answer


Well, better late than never:

function mandelbrot(x0,y0,side,N=800,L=55,R=3.)
    m = [0 for i=1:N,j=1:N]
    delta = side/N
    for i=1:N, j=1:N
        c = x0+delta*i+(y0+delta*j)*im
        z, h = 0+0*im, 0
        while (h<L) && (abs(z)<R)
            z = z^2+c
    return m
m = mandelbrot(-n/1.3,-n/2, n)
using Winston, Color
title("Mandelbrot Set")

Colormap Mod. :

function RGB_cm()
    colormap = [RGB(0,0,0) for t=1:255*5]
    rgb = [255,0,0]
    for t in 0:(255*5-1)
    c = [0, 0, 0]
    i = ifloor(t/255)
    c[(i+3)%3!=0?(i+3)%3:3] = (-1)^i
    colormap[t+1] = RGB(rgb[1],rgb[2],rgb[3])
    colormap[(end-25):end] = RGB(0,0,0)
    return colormap
c = RGB_cm()


Mandelbrot Set

share|improve this answer
Should I byte-count only the first program or both? – Mark Jeronimus Mar 29 '14 at 10:10
I think both, because without the color map mod the image would not satisfy the rules. – CCP Mar 29 '14 at 15:35

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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