JavaScript Implementation of Problem 12

View source code here on GitHub!

p0012()

Project Euler Problem 12

Problem:

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?

Returns:

number --

 1/**
 2 * Project Euler Problem 12
 3 *
 4 * Problem:
 5 *
 6 * The sequence of triangle numbers is generated by adding the natural numbers. So
 7 * the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten
 8 * terms would be:
 9 *
10 * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
11 *
12 * Let us list the factors of the first seven triangle numbers:
13 *
14 * .. code-block::
15 *
16 *      1: 1
17 *      3: 1,3
18 *      6: 1,2,3,6
19 *     10: 1,2,5,10
20 *     15: 1,3,5,15
21 *     21: 1,3,7,21
22 *     28: 1,2,4,7,14,28
23 *
24 * We can see that 28 is the first triangle number to have over five divisors.
25 *
26 * What is the value of the first triangle number to have over five hundred
27 * divisors?
28 *
29 * @return {number}
30 **/
31exports.p0012 = function() {
32    let num = 0;
33    for (let x = 1; ; x++) {
34        num += x;
35        if ([...factors.properDivisors(num)].length > 500) {
36            return num;
37        }
38    }
39    return -1;
40};
41
42const factors = require('./lib/factors.js');

Tags: optimization