Project Euler: Problem 12

Here’s the next Euler problem:

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 first thing to note is we’re probably going to need to generate a sequence of triangle numbers. Lucky for us, triangle number t[n] is equal to t[n - 1] + n. This can be translated into an unfolding sequence fairly easily:

let TriangleNumbers =
    (0UL, 1UL) |> Seq.unfold (fun (x, y) -> Some(x + y, (x + y, y + 1UL)))

Then the tricky part: testing for the number of divisors each number has. My initial solution to this problem was the following:

open System

let NumDivisors n =
    let mutable i = 1UL
    let mutable c = 0UL
    while i <= uint64(Math.Sqrt(float(n))) do
        if n % i = 0UL then
            c <- c + 1UL
        i <- i + 1UL
    c * 2UL

This is not a particularly clever solution, but it turns out it does the trick. We can ask for the first triangle number with more than 500 divisors like so:

let result = TriangleNumbers |> Seq.find (fun x -> NumDivisors x > 500UL)

The solution returns in a few seconds, which is more than acceptable, especially considering I haven’t even bothered yet trying to find something more efficient or clever (chances are doing so would involve math… shudder…).