title: Optimizing Mandelbrot fractal
body: <p>This is a code that outputs in a .ppm file the mandelbrot fractal. How can I optimize this?</p>
  
  <pre><code>#include&lt;bits/stdc++.h&gt;
  using namespace std;
  
  int findMandelbrot(double cr, double ci, int max_iterations)
  {
      int i = 0;
      double zr = 0.0, zi = 0.0;
      while (i &lt; max_iterations &amp;&amp; zr * zr + zi * zi &lt; 4.0)
      {
          double temp = zr * zr - zi * zi + cr;
          zi = 2.0 * zr * zi + ci;
          zr = temp;
          ++i;
      }
      return i;
  }
  
  double mapToReal(int x, int imageWidth, double minR, double maxR)
  {
      double range = maxR - minR;
      return x * (range / imageWidth) + minR;
  }
  
  double mapToImaginary(int y, int imageHeight, double minI, double maxI)
  {
      double range = maxI - minI;
      return y * (range / imageHeight) + minI;
  }
  
  int main()
  {
      ifstream f("input.txt");
      int imageWidth, imageHeight, maxN;
      double minR, maxR, minI, maxI;
  
      if (!f)
      {
          cout &lt;&lt; "Could not open file!" &lt;&lt; endl;
          return 1;
      }
  
      f &gt;&gt; imageWidth &gt;&gt; imageHeight &gt;&gt; maxN;
      f &gt;&gt; minR &gt;&gt; maxR &gt;&gt; minI &gt;&gt; maxI;
  
      ofstream g("output_image.ppm");
      g &lt;&lt; "P3" &lt;&lt; endl;
      g &lt;&lt; imageWidth &lt;&lt; " " &lt;&lt; imageHeight &lt;&lt; endl;
      g &lt;&lt; "255" &lt;&lt; endl;
  
  
      double start = clock();
  
      for (int i = 0; i &lt; imageHeight; i++)
      {
          for (int j = 0; j &lt; imageWidth; j++)
          {
              double cr = mapToReal(j, imageWidth, minR, maxR);
              double ci = mapToImaginary(i, imageHeight, minI, maxI);
  
              int n = findMandelbrot(cr, ci, maxN);
  
              int r = ((int)sqrt(n) % 256);
              int gr = (2*n % 256);
              int b = (n % 256);
  
              g &lt;&lt; r &lt;&lt; " " &lt;&lt; gr &lt;&lt; " " &lt;&lt; b &lt;&lt; " ";
          }
          g &lt;&lt; endl;
  
          if(i == imageHeight / 2) break;
      }
  
      cout &lt;&lt; "Finished!" &lt;&lt; endl;
  
      double stop = clock();
  
      cout &lt;&lt; (stop-start)/CLOCKS_PER_SEC;
      return 0;
  }
  </code></pre>
  
  <p>I go until imageHeight / 2 because in a photoshop I can just copy the other half.
  I was thinking about loghartimic power but tried something and only works with integers...</p>