{ The Computer Language Shootout
  http://shootout.alioth.debian.org

  contributed by Ales Katona
  modified by Vincent Snijders
}

program mandelbrot;




{$FPUTYPE SSE2}{$I-}


var n, x, y, bits,bit: Longint;
    Cx, Cy: double;

procedure CalculatePoint; nostackframe;
const
  Limit: double =4.0;
  zero: double = 0.0;
var
  i: longint;
  GC,
  Zr, Zi, Ti, Tr: Double;
  
begin
  Zr := zero;  Zi := Zr;
  Tr := Zr; Ti := Zi;
  GC := Limit;
  i := 50;
  repeat
    Zi := 2 * Zr * Zi + Cy;
    Zr := Tr - Ti + Cx;
    Tr := Zr * Zr;
    Ti := Zi * Zi;
    if  (Tr + Ti) >= GC then begin
      bits := bits xor bit;
      exit;
    end;
    dec(i);
  until  (i=0);
end;


{$FPUTYPE X87}
var
    ss : shortstring;
    
    bb : byte absolute ss;
    textbuf:array[0..8191] of char;
    
    
procedure writeSS;
begin
  write(ss);
end;


procedure writech( const ch : char);inline;
begin

   if length(ss)=250 then begin
     writess;
     bb:=1;
   end else begin
      inc(bb);
   end;
   ss[bb]:=ch;

end;


begin
  Val(ParamStr(1), n);
  settextbuf(output,textbuf,sizeof(textbuf));

  writeln('P4');
  writeln(n,' ',n);
  ss:='';
  for y := 0 to n-1 do
  begin
    Cy := y * 2 / n - 1;
    bits := 255;  bit := 128;
    for x := 0 to n-1 do
    begin
      Cx := x * 2 / n  - 1.5;

      CalculatePoint;

      if bit > 1 then
        bit := bit shr 1
      else
      begin
        writech(chr(bits));
        bits := 255;  bit := 128;
      end;
    end;
    if bit < 128 then writech(chr(bits xor((bit shl 1)-1)));
  end;
  write(ss);
end.
