|
| 1 | +/** |
| 2 | + * Problem 12 - Highly divisible triangular number |
| 3 | + * |
| 4 | + * https://projecteuler.net/problem=11 |
| 5 | + * |
| 6 | + * The sequence of triangle numbers is generated by adding the natural numbers. |
| 7 | + * So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. |
| 8 | + * |
| 9 | + * The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... |
| 10 | + * Let us list the factors of the first seven triangle numbers: |
| 11 | + * |
| 12 | + * 1: 1 |
| 13 | + * 3: 1,3 |
| 14 | + * 6: 1,2,3,6 |
| 15 | + * 10: 1,2,5,10 |
| 16 | + * 15: 1,3,5,15 |
| 17 | + * 21: 1,3,7,21 |
| 18 | + * 28: 1,2,4,7,14,28 |
| 19 | + * |
| 20 | + * We can see that 28 is the first triangle number to have over five divisors. |
| 21 | + * |
| 22 | + * What is the value of the first triangle number to have over five hundred divisors? |
| 23 | +*/ |
| 24 | + |
| 25 | +/** |
| 26 | + * Gets number of divisors of a given number |
| 27 | + * @params num The number whose divisors to find |
| 28 | + */ |
| 29 | +const getNumOfDivisors = (num) => { |
| 30 | + // initialize numberOfDivisors |
| 31 | + let numberOfDivisors = 0 |
| 32 | + |
| 33 | + // if one divisor less than sqrt(num) exists |
| 34 | + // then another divisor greater than sqrt(n) exists and its value is num/i |
| 35 | + const sqrtNum = Math.sqrt(num) |
| 36 | + for (let i = 0; i <= sqrtNum; i++) { |
| 37 | + // check if i divides num |
| 38 | + if (num % i === 0) { |
| 39 | + if (i === sqrtNum) { |
| 40 | + // if both divisors are equal, i.e., num is perfect square, then only 1 divisor |
| 41 | + numberOfDivisors++ |
| 42 | + } else { |
| 43 | + // 2 divisors, one of them is less than sqrt(n), other greater than sqrt(n) |
| 44 | + numberOfDivisors += 2 |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + return numberOfDivisors |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Loops till first triangular number with 500 divisors is found |
| 53 | + */ |
| 54 | +const firstTriangularWith500Divisors = () => { |
| 55 | + let triangularNum |
| 56 | + // loop forever until numOfDivisors becomes greater than or equal to 500 |
| 57 | + for (let n = 1; ; n++) { |
| 58 | + // nth triangular number is (1/2)*n*(n+1) by Arithmetic Progression |
| 59 | + triangularNum = (1 / 2) * n * (n + 1) |
| 60 | + if (getNumOfDivisors(triangularNum) >= 500) return triangularNum |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +export { firstTriangularWith500Divisors } |
0 commit comments