the-honk/challenges/euler/src/12 - Highly divisible triangular number.ts

60 lines
1.7 KiB
TypeScript

// 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?
export {};
/**
* Find the factors of a n
*/
const factorsOf = (n: number) => {
const isEven = n % 2 === 0;
const max = Math.sqrt(n);
const inc = isEven ? 1 : 2;
const factors = [1, n];
for (let curFactor = isEven ? 2 : 3; curFactor <= max; curFactor += inc) {
if (n % curFactor !== 0) continue;
factors.push(curFactor);
let compliment = n / curFactor;
if (compliment !== curFactor) factors.push(compliment);
}
return factors;
};
/**
* Find the nth triangle number
* @see https://www.mathsisfun.com/algebra/triangular-numbers.html
*/
const triangleNumber = (n: number) => (n * (n + 1)) / 2;
/**
* Find the first triangle number with over n divisors
*/
const firstTriangleWithOverNDivisors = (n: number) => {
let divisorCountFound = false;
let i = 1;
while (!divisorCountFound) {
const triangle = triangleNumber(i);
const factors = [...factorsOf(triangle)];
i++;
if (factors.length > n) {
divisorCountFound = true;
return triangle;
}
}
};
// Output
console.log(firstTriangleWithOverNDivisors(500));