The sequence of triangle numbers is generated by adding the natural numbers. So the triangle number would be . The first ten terms would be:
Let us list the factors of the first seven triangle numbers:
We can see that 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?
Let’s solve this problem using Julia
We can start by creating two functions
TriangleNumber(n): This function will compute the nth triangle number
CountDivisors(n): This function will compoute the number of divisors of n.
Code
functionTriangleNumber(n)# Compute the nth triangle number triangle_number =1if n ==1return triangle_numberelsefor i =2:n triangle_number = triangle_number + iendendreturn triangle_numberend
TriangleNumber (generic function with 1 method)
Let’s check our function to check for the correct triangle number
Code
println("The 5th triangle number is ", TriangleNumber(5))println("The 6th triangle number is ", TriangleNumber(6))println("The 7th triangle number is ", TriangleNumber(7))
The 5th triangle number is 15
The 6th triangle number is 21
The 7th triangle number is 28
Now let’s create the CountDivisors(n) function
Code
functionCountDivisors(n) count =1if n ==1 count =1elseif n ==2 count =2elsefor i =2:nif n%i ==0 count = count +1endendendreturn countend
CountDivisors (generic function with 1 method)
Let’s test this function to check for the correct number of divisors
Code
println("3 has ", CountDivisors(3), " divisors")println("4 has ", CountDivisors(4), " divisors")println("28 has ", CountDivisors(28), " divisors")
3 has 2 divisors
4 has 3 divisors
28 has 6 divisors
Let’s now run a script to compute the first triangle with over divisors
Code
index =0triangle_number =0whiletrue index = index +1 triangle_number =TriangleNumber(index)ifCountDivisors(triangle_number) >500breakendendtriangle_number
76576500
Code
CountDivisors(76576500)
576
Therefore the first triangle number to have over 500 divisors is and it has divisors.