A triangle number is the number of dots that form a triangle. Find how many triangles exist from triangle number 1 to the first triangle with triangle number >= 500.
In the illustration below, triangle numbers are: 1, 3, 6, 10, and would continue with 15, 21, 28, 36, …
. . . . . . . . . . . . . . . . . . . . 1 3 6 10
First, determine the number of dots for each triangle i. That happens to be the sum of numbers between 1 and i, for a triangle i.
i = 1, 1=1
i = 2, 1+2=3
i = 3, 1+2+3=6
i = 4, 1+2+3+4=10
function getTriangleNumber(t) { return (t*(t+1))/2 } function getTriangles(number) { let triangles = [] for (let i = 1; true; i++) { let n = getTriangleNumber(i) triangles.push(n) if (n >= number) { return triangles.length } } return -1 }
Another approach is to keep a running sum of triangle numbers. A triangle number for triangle i is i + triangle number at i-1.
function getTriangles(number) { let triangles = [] let n = 0 for (let i = 1; true; i++) { let n = n + i triangles.push(n) if (n >= number) { return triangles.length } } return -1 }