From df525339136fa9f7a1b237c76f7d12ef462c4181 Mon Sep 17 00:00:00 2001 From: newt Date: Wed, 9 Oct 2024 18:02:36 +0100 Subject: [PATCH] (euler): #12 --- ...12 - Highly Divisible Triangular Number.ts | 39 +++++++++++++++++++ euler/tsconfig.json | 3 +- 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 euler/src/12 - Highly Divisible Triangular Number.ts diff --git a/euler/src/12 - Highly Divisible Triangular Number.ts b/euler/src/12 - Highly Divisible Triangular Number.ts new file mode 100644 index 0000000..91f6f1f --- /dev/null +++ b/euler/src/12 - Highly Divisible Triangular Number.ts @@ -0,0 +1,39 @@ +export {}; + +const factorsOf = (num: number) => { + const isEven = num % 2 === 0; + const max = Math.sqrt(num); + const inc = isEven ? 1 : 2; + const factors = [1, num]; + + for (let curFactor = isEven ? 2 : 3; curFactor <= max; curFactor += inc) { + if (num % curFactor !== 0) continue; + factors.push(curFactor); + + let compliment = num / curFactor; + if (compliment !== curFactor) factors.push(compliment); + } + + return factors; +}; + +// https://www.mathsisfun.com/algebra/triangular-numbers.html +const nthTriangleNumber = (n: number) => (n * (n + 1)) / 2; + +const firstTriangleWithOverNDivisors = (n: number) => { + let divisorCountFound = false; + let i = 1; + + while (!divisorCountFound) { + const triangle = nthTriangleNumber(i); + const factors = [...factorsOf(triangle)]; + i++; + + if (factors.length > n) { + divisorCountFound = true; + return triangle; + } + } +}; + +console.log(firstTriangleWithOverNDivisors(500)); diff --git a/euler/tsconfig.json b/euler/tsconfig.json index 4f16804..7345e25 100644 --- a/euler/tsconfig.json +++ b/euler/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "target": "es5", "module": "commonjs", - "outDir": "build" + "outDir": "build", + "downlevelIteration": true }, "include": ["src/**/*.ts"], "exclude": ["node_modules"]