Euler Problem 12 takes us to the realm of triangular numbers and proper divisors.

The image on the left shows a hands-on method to visualise the number of divisors of an integer. Cuisenaire rods are learning aids that provide a hands-on way to explore mathematics.

## Euler Problem 12 Definition

The sequence of triangle numbers is generated by adding the natural numbers. So the 7^{th} triangle number would be . The first ten terms would be: 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?

## Solution

Vishal Kataria explains a simple method to determine the number of divisors using prime factorization as explained by in his video below. The prime factorization of is given by:

The number of proper divisors is:

The code reuses the prime factorisation function developed for Euler Problem 3. This function results in a vector of all prime factors, e.g. the prime factors of 28 are 2, 2 and 7.

The code to solve this problem determines the values for alpha using the run length function. This function counts the number of times each element in a sequence is repeated. The outcome of this function is a vector of the values and the number of times each is repeated. The prime factors of 28 are 2 and 7 and their run lengths are 2 and 1. The number of divisors can now be determined.

The code to solve Euler Problem 12 is shown below. The loop continues until it finds a triangular number with 500 divisors. The first two lines increment the index and create the next triangular number. The third line in the loop determines the number of times each factor is repeated (the run lengths). The last line calculates the number of divisors using the above-mentioned formula.

i <- 0 divisors <- 0 while (divisors < 500) { i <- i + 1 triangle <- (i * (i+1)) / 2 pf <- prime.factors(triangle) alpha <- rle(pf) divisors <- prod(alpha$lengths+1) } answer <- triangle print(answer)

Pingback: Euler Problem 12: Highly Divisible Triangular Number - Use-R!Use-R!

Pingback: Euler Problem 12: Highly Divisible Triangular Number | A bunch of data

Pingback: Euler Problem 12: Highly Divisible Triangular Number – Mubashir Qasim

Well, as long as you’ve used one of my favorite quick-analysis functions, rle, let me put my plug in for my augmented function, “seqle” . It’s available in the CRAN package “cgwtools.” seqle can not only look for run lengths, but can be set to look for runs of constant “slope,” e.g. numbers whose differences remains a specified constant. seqle(x,0) is the same as rle(x) .

Hi Carl, that is a very useful function indeed.

I analyse a lot of SCADA data. These are high frequency time series generated by production processes.