Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Is there something tricky that I'm not catching? There probably is... (<strong>edit:</strong> yes, there is!)</p> <pre><code>class AllInts { public static void main(String[] args) { // wrong -- i &lt;= Integer.MAX_VALUE will never be false, since // incrementing Integer.MAX_VALUE overflows to Integer.MIN_VALUE. for (int i = Integer.MIN_VALUE; i &lt;= Integer.MAX_VALUE; i++) { System.out.println(i); } } } </code></pre> <p>Since the printing is the bottleneck, a buffer would improve the speed quite a lot (I know because I just tried it):</p> <pre><code>class AllInts { public static void main(String[] args) { // a rather large cache; I did no calculations to optimize the cache // size, but adding the first group of numbers will make the buffer // as large as it will ever need to be. StringBuilder buffer = new StringBuilder(10000000); int counter = 0; // note that termination check is now &lt; // this means Integer.MAX_VALUE won't be printed in the loop for (int i = Integer.MIN_VALUE; i &lt; Integer.MAX_VALUE; i++) { buffer.append(i).append('\n'); if (++counter &gt; 5000000) { System.out.print(buffer); buffer.delete(0, buffer.length()-1); counter = 0; } } // take care of the last value (also means we don't have to check // if the buffer is empty before printing it) buffer.append(Integer.MAX_VALUE); System.out.println(buffer); } } </code></pre> <p>Also, this version will actually terminate (thanks to Daniel Lew for pointing out that there was, in fact, something tricky that I wasn't catching).</p> <p>The total run time for this version (run with -Xmx512m) was 1:53. That's over 600000 numbers/second; not bad at all! But I suspect that it would have been slower if I hadn't run it minimized.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload