Project Euler problem 12
February 20th, 2009 at 1:15 pmI’ve got hooked to Project Euler this week, after hearing good stuff about it for a long time. I’ve already solved the first 16 problems, and it has been lots of fun so far.
Most of the problems I’ve encountered are trivial, and can be either solved by a simple brute-force approach or by using a known mathematical formula. Besides, Python’s built-in and efficient arbitrary-precision arithmetic makes many problems very trivial (such as 16 – the sum of digits in the number
).
The first problem that gave me some hard time was 12 – I just couldn’t brute-force it. Eventually, a couple of insights led me to the solution, which was very satisfying.
Below are some tips for solving it, though I don’t provide the full solution.
The most important insight is that you don’t have to enumerate all the numbers up to
and check if they divide it, counting those that do.
A faster method is to factorize N, and use the divisor function to compute the amount of divisors.
If the factorization of N is:

Where
are the prime factors and
are their exponents, then the total amount of divisors of N is:

Even with the crappy factorizing routine I used, this produces the amount of divisors for a given number much faster than the naive method.
The second key insight (without which it would also take too long to solve this problem) is that since we’re looking for the smallest number with 500 divisors, it will definitely have small prime factors. So I just threw away anything that didn’t divide by 2, 3, 5 and so on. After a few experimentations, I had an algorithm that finds the desired number in about 4 seconds.
Related posts:

February 20th, 2009 at 20:55
I’ve been enjoying project euler occasionally as well.
p25 and p26 were good, for 25 I ported the logarithmic complexity Fibonacci routine from SICP exercise 1.19 (even though it makes the program slower), and 26 is well suited to python.
February 21st, 2009 at 13:26
I really don’t understand what’s the problem here – I brute forced it in C#, counting all factors till sqrt(n) and doubling by 2. It takes 2 seconds to run, in Debug mode.
So far I’ve done 1-16, 20, 25 (I’m going through them on the order of difficulty, not ID). Funny that the last problem I tackled, #15, is the one I recently blogged about regardless of Project Euler.
I’m still waiting to reach the more difficult problems. Thanks for the pointer Eli.
February 21st, 2009 at 18:02
@Ron,
I wonder why it didn’t work out for me then, hmm… Never mind, it’s a good thing – I had more fun finding a shorter way
What’s your username on Project Euler? Mine’s eliben.
February 21st, 2009 at 19:13
ripper234 :0
February 23rd, 2009 at 07:28
My brute force in C is a real stupid one, and takes 30 minutes !
(I’m bsergean there).
Coding on Project Euler is really cool, you can leave it for a long time and come back, you will still enjoy it. And it really feel good to solve a new problem
- Benjamin