JavaScript Implementation of Problem 34

View source code here on GitHub!

Includes

Problem Solution

p0034()

Project Euler Problem 34

This ended up being a filtering problem. The problem with my solution is that I am not satisfied with my filter at all. I feel like there is a more efficient way to go about it.

Problem:

145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.

Find the sum of all numbers which are equal to the sum of the factorial of their digits.

Note: as 1! = 1 and 2! = 2 are not sums they are not included.

Returns:

number --

 1/**
 2 * Project Euler Problem 34
 3 *
 4 * This ended up being a filtering problem. The problem with my solution is that I
 5 * am not satisfied with my filter at all. I feel like there is a more efficient
 6 * way to go about it.
 7 *
 8 * Problem:
 9 *
10 * 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
11 *
12 * Find the sum of all numbers which are equal to the sum of the factorial of
13 * their digits.
14 *
15 * Note: as 1! = 1 and 2! = 2 are not sums they are not included.
16 *
17 * @return {number}
18 */
19exports.p0034 = function() {
20    let answer = 0;
21    for (let x = 10; x < 100000; x += 1) {
22        const xs = x.toString();
23        let sum = 0;
24        for (let i = 0; i < xs.length; i += 1) {
25            sum += Mathematics.factorial(Number(xs[i]));
26        }
27        if (sum == x) {
28            answer += x;
29        }
30    }
31    return answer;
32};
33
34const Mathematics = require('./lib/math.js');

Tags: factorial, digit-sum