Project Euler: Problem 12 in Ruby

I took a couple swings at problem #12 before I finally got it. I’m definitely over my head mathematically, but that’s part of the fun and I’m certainly learning a lot along the way. Big thanks to Dr. Math for his excellent explanation of how to find a number’s number of factors.

Problem #12

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

Surely it’s not the perfect solution, but it ran in under 4 seconds on ruby 1.9, so I’m happy with it. Looking at it now, it all seems obvious but I must have started over at least a dozen times. Here are a few recurring Project Euler themes I’ve picked up on, as applied to this problem.

  1. Like every other Project Euler problem, don’t repeat your calculations, cache it! Prime number computation is heavy.
  2. If you don’t have to store something don’t. In this case it’s enough to count the distinct factors, you don’t have to store them.
  3. Cut down your data set. Since we’re looking for a number that has over 500 factors then we don’t need to start looking until after the 500th triangle.

Enough talk, here’s the code:

require 'mathn'

primer  = Prime.new
primes  = [ primer.next ]
seed    = 500
n       = (seed * (seed + 1)) / 2
i       = seed + 1

def count_prime_factors primer, primes, n
  total = 1
  max   = Math.sqrt(n).to_i

  while primes.last < max
    primes << primer.next
  end
  
  primes.each do |i|
    count = 0
    while n % i == 0
      n = n / i
      count += 1
    end
    if count > 0
      total *= count + 1
    end
  end

  total
end

while(count_prime_factors(primer, primes, n) < seed)
  n += i
  i += 1
end

puts n