What’s a triangular number? It is the sequence found by summing all the natural numbers, for example the third number is

This also has closed form
I started with a brute force approach – iterate through the triangular numbers and test if the number of divisors is greater than 500. I’m using the “numbers” package’s Sigma function to implement divisor function
library(numbers) triangular.number <- function(number) { number = (number * (number + 1)) / 2 } num.factors <- 0 i <- 1 while (num.factors < 500) { num.factors <- (Sigma((triangular.number(i)), k = 0)) print(triangular.number(i)) i <- i + 1 }
Not terribly efficient but it gets the correct answer. So how can we improve the algorithm? Reducing the number of times we repeat the loop would be a good place to start.
Now,