Project Euler 12

I was recently going through some old Project Euler solutions, and noticed that my solution to problem 12 was never optimized. The problems asks:

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …

Let us list the factors of the first seven triangle numbers:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

The way I originally solved this problem was a brute-force approach following this basic logic:

  1. Calculate next triangle number
  2. Try dividing number by every integer smaller than the number
  3. Count the number of integers that divide evenly
  4. Go to step 1 and repeat until divisors are greater than 500

This process yielded the results, but it is far from elegant or optimized. it took 14 minutes to calculate the answer! I knew that dividing by each number was a waste; there had to be a better way.

Although I didn’t know it, I felt fairly certain that there was a relationship between prime factors and the number of divisors. It turns out I was right. There is a trick to calculate the number of divisors if you know the prime factors.

Using the number 28 as an example, we can find that the prime factors are 2, 2, and 7, which can be written as 22 × 71. Interestingly, if we take the exponents, add 1 to each, and then multiply them together, we can calculate the number of divisors. For this example, this becomes (2+1) × (1+1), which is 2 × 3, which equals 6. (This is also mentioned in the Wikipedia article for divisor briefly in the section titled ‘Further notions and facts’).

Equipped with this knowledge, I was able to devise a more efficient method to solve this problem:

  1. Pre-calculate primes up to x amount (to save effort recomputing each time)
  2. Calculate next triangle number that is divisible by 3 or 5 (I found a pattern that the most divisible triangle numbers were divisible by 3 or 5)
  3. Go through primes and divide number by primes until number equals 1
  4. Convert the prime factors to divisors
  5. Go to step 1 and repeat until divisors are greater than 500

While this method is more complex, it yielded great results. Once I was done refining this method, I got the compute time down to .086 seconds. That is a very substantial improvement!

The interesting part of the code is the findDivisors function, seen below.

int findDivisors(int input, int *primes, int primesToFind)
{
    int i, count=1;
    int primeCount[primesToFind];
    for (i=0; i<primesToFind; i++)
    primeCount[i] = 0;

    // Prime factorization
    while (input != 1)
        for (i=0; i<primesToFind; i++)
            if (input % primes[i] == 0)
            {
                input = input / primes[i];
                primeCount[i]++;
            }

    // Convert prime factorization to divisors
    for (i=0; i<primesToFind; i++)
        if (primeCount[i] > 0)
            count *= (primeCount[i]+1);

    return count;
}

In this function, the inputs are:

  • The triangle number (input)
  • The array of pre-calculated prime numbers (primes)
  • The number of primes in the array (primesToFind)

As the division of primes occurs, I keep track in a separate array (primeCount) how many times a given prime index is used to divide. This keeps track of the prime factorization I talked about earlier so we can finally compute the number of divisors. Once computed, we pass back the count, and the program moves on to the next triangle number.

So there you have it. My entire solution is available on my GitHub page.

Emacs on Mac OS X

carbon-emacs-iconAt work I use a Linux work station a lot, and one of the things I really enjoy is that when I use Emacs from the command line, it opens up the graphical user interface. This, of course, is not the behavior on OS X. Additionally, the version that ships with Mac OS X is woefully out of date (version 22.1.1 at the time of writing).

I decided to do something about it, and grabbed an up-to-date build of Emacs from emacsformacosx.com. By default, it gets installed in /Applications, which will work just fine. It provides a graphical version of Emacs with support for normal Mac OS X short cuts, like command-c, etc.

But, Michael, how does this solve the problem of the Emacs from the command line being out of date? Well, Inside the application bundle is the Emacs executable that can be run from the command line, sans GUI. All you have to do is create an alias with this code (in my case, I made a bash script that resides in my ~/.bin named ’emacs’) with the following code:

#!/bin/sh
if
    [ -z "$SSH_CONNECTION" ]
then
    /Applications/Emacs.app/Contents/MacOS/Emacs "$@"
else
    /Applications/Emacs.app/Contents/MacOS/Emacs -nw "$@"
fi

This makes it so that if the terminal detects that you are running over an SSH (non-graphical) connection, it will run the non-windowed version of Emacs, otherwise it will launch the graphical version. It works just like it does in most Linux distros, and is a real pleasure to use!

Arkanoid Cocktail Cabinet

Arkanoid-Logo-New

About 13 years ago (2001), my brother, dad and I embarked on a mission to create some arcade cocktail cabinets. My brother had bought some vintage arcade games at auction, and we both decided that it would be fun to own brand-new cocktail tables.

We got my dad on-board with the idea, which was probably the most important part, since he had all the tools and know-how. And if we were going to build 2, we might as well build more. We ended up creating 6 cocktail cabinets; one for each sibling in our family, one for a cousin, and another for a neighbor. This original endeavor is somewhat documented on my very old personal site.

The Cabinet

The first thing we did is measure an actual cocktail cabinet that we found at a local Marie Calendar’s. The cabinet was actually pretty terrible. It didn’t appear to be authentic, and was in bad condition. That aside, it gave us some basic ideas for size and construction.

IM000185

We build a rough prototype out of some old plywood that we had lying around in the garage. It was very crude, but it helped us cement down some measurements and figure out how we would do this with the actual cabinets. It was quickly built with ugly butt joints and no thought to finish in one evening. We then wrote down some final measurements and made plans for how to construct the final cabinets.

IM000209

For the final cabinets, we used plywood with oak veneer. We used 3/4 throughout with the exception of the top which was 3/4 and 1/4 laminated together to make a substantial 1 inch thick surface. The pieces were all cut out on the table saw. We decided to use dados throughout the construction in order to eliminate the need to nails and screws. We wanted the finished product to look elegant and not cheap.

IM000270

The bottom piece is made of particle board with a melamine layer on both sides. holes were pre-cut for a speaker, AC receptical, and fan. The power supply was also mounted to the bottom piece.

IM000314

All of the sides were fitted together and glued. The dados provided strong joints once glued. For the door, we attached it using european hinges instead of unsightly piano hinges that are common on arcade cabinets. Since this is for personal use, we made no effort to make the cabinet lock. The edges were all routed with a groove in order to accept t-molding, however some of the cabinets were fitted with edge-tape veneer instead.

IM000215

The tube is actually a cheap 19 inch CRT TV that we bought from Fry’s and then converted to accept the arcade video signals. For some reason, they sales person didn’t believe us when we asked for 6 19 inch CRT TVs…

IM000516

Of all of the cabinets, only 2 got 100% completed; mine, an Arkanoid, and my sister’s, a Mrs. Pac-Man. My other sister, who was in college at the time, didn’t want her’s put together since she had no place to put it, so it sat in storage in pieces.

Ten Years Later

My sister was hosting a family reunion, and wanted her cocktail cabinet for the kids to play on. I had agreed to finish her cabinet for her when she had a permanent dwelling. The time had come, but I didn’t have enough lead time to prepare it for the reunion. En lieu of her cabinet, I gave her my Arkanoid, leaving me with the unassembled cabinet in storage.

Over the last month or two I’ve been collecting all the pieces I needed in order to complete this game, including power supply, controllers, PCB, buttons, and the control panel overlay.

IM000213

I assembled the cabinet by simply gluing the awaiting pieces together. It went together perfectly. Even the hardware for hinges was already in place in storage, so there was little to do there. This cabinet had its edged veneered instead of using t-molding. This is was actually preferable to me as I found that I didn’t like the look of the t-molding on my original cabinet after a while. I stained it using a red-wood colored Minwax. This time I opted for a red stain over the brown that I used for my original. From there I spent a weekend putting a clear coat of Deft over it.

IMG_1606_edited

I took the original design file for the control panel overlay that I made back 10 years ago, and updated it significantly. I cleaned up some mistakes, and updated some of the graphics to look cleaner than before. (Before, I barely knew how to use Illustrator). The first time around, I printed them on photo-paper and put them under a thin sheet of plexi-glass. This time, I had them printed at ArcadeOverlays.com, and they turned out great!

IM000303_edited

We fitted all of the cabinets with Jamma. This made it easy to swap games in and out if we ever needed to. The Arkanoid 1 PCB needed a custom Jamma adapter whereas Arkanoid 2 comes with a Jamma connector as standard. I build a converter board for my Arkanoid 1 PCB so I could quickly switch between Arkanoid 1 and 2.

IMG_1607

I spent about an hour putting all the connectors on the wiring harness, and hooking up all the controls, power, and monitor. I hooked it all up on the bench, and verified that everything worked, and it did! Another change I made was using an LED strip for the panel illumination instead of bulky, hot incandescent lights.

IMG_1658

The control panels are made from sheet steel. I had a friend who works in a metal shop who bent them on his brake for me. I then drilled all the holes using a template I made in Illustrator based off of the design I had printed, and drilled the holes on a drill press. It was panted with black lacquer, and then I carefully placed the CPO sticker on. That was the most nerve wracking part!

IMG_1688 edited

Once I had all the electronics working, and ready to go, all that was left was to stick it into the box. I made a little box that you can see on the left for holding the PCBs. It fits 3; Arkanoid 1, Arkanoid 2 and Tournament Arkanoid. Everything fit like a glove!

IMG_1685_edited

I made some top artwork a while ago in anticipation of this project. The design was meant to be retro, and a little cheeky. I’m not sure that will be a permanently displayed… It was printed on a friend’s large format printer, and then I cut it out with an exacto knife. I have a new design that’s a little less in-your-face that I’m contemplating printing…

The Finished Product

IMG_1683_small

All-in-all, the cabinet turned out great. I’m very pleased with the look of the cabinet, as well as with the game itself. I quite enjoy Arkanoid, and enjoy having Arkanoid 2. It’s a little different but still familiar. I don’t think I’ll get tired of it soon.

© 2007-2015 Michael Caldwell