The Time I Won The Programming Contest

It was a simple contest: Write code that displays the first 100 prime numbers. The person who wrote the fastest code won.

Such a challenge today wouldn’t be worthy; you’d need to display several thousand primes to detect any speed differences between systems. That’s because today’s computers are so fast that 100 primes appear in the blink of an eye (well, providing you didn’t completely screw up the code). In fact, the main thing slowing down a program of this type is output: It probably takes longer for a computer today to generate the text output for 100 primes than it does for the code to calculate the values.

Back in the early 1980s, processor speed and screen output were both hurdles. So as long as your code ran on the same computer, or two identical systems side-by-side, you could judge which was faster. For the 100 Primes contest, two computers were setup side-by-side. The program name was typed at the command prompt, then both Enter keys pressed simultaneously.

The results were surprising: My code generated 100 primes quickly, scrolling output the screen in a swift cascade of numbers. It looked like a tall ship’s sail unfurling. It was beautiful.

The other programs, running on the other computer, spurt out one prime number at a time, fast at first and then more slowly. My code’s output took one third the time. That surprised everyone, most of whom were professional programmers.

“How did Gookin do it?” they wondered. Then I showed them the code, which you see below.

#include <stdio.h>

int main()
{
    puts("2\t3\t5\t7\t11\t13\t17\t19\t23\t29");
    puts("31\t37\t41\t43\t47\t53\t59\t61\t67\t71");
    puts("73\t79\t83\t89\t97\t101\t103\t107\t109\t113");
    puts("127\t131\t137\t139\t149\t151\t157\t163\t167\t173");
    puts("179\t181\t191\t193\t197\t199\t211\t223\t227\t229");
    puts("233\t239\t241\t251\t257\t263\t269\t271\t277\t281");
    puts("283\t293\t307\t311\t313\t317\t331\t337\t347\t349");
    puts("353\t359\t367\t373\t379\t383\t389\t397\t401\t409");
    puts("419\t421\t431\t433\t439\t443\t449\t457\t461\t463");
    puts("467\t479\t487\t491\t499\t503\t509\t521\t523\t541");

    return(0);
}

This code did not cheat! Remember, the program’s goal was to display the first 100 primes. It wasn’t to write a routine that first calculates and then displays the primes, although that was the implication and the path the other programmers chose to follow. So although there was some upset, I was congratulated on being clever.

My point is this: Don’t lose sight of the Big Picture. It’s very easy as a programmer to over-complicate issues. You can speed hours working on a gorgeous algorithm that works exactly as intended. If you’re like me, your brain probably loves such puzzles. That’s not going to help you, however, when an easier, more obvious solution is at hand. Don’t be afraid to consider that easier solution!

Leave a Reply