Digit factorials: Find the Sum of All the Curious Numbers

  • 时间:2020-09-10 12:45:51
  • 分类:网络文摘
  • 阅读:115 次

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.

Pre-computing the Digit factorials

The factorials we all need to know are from 0! to 9!. Therefore, we can pre-compute the digital factorials and store them in a dictionary (or hash map).

1
2
3
4
5
6
7
let factorials = {};
let s = 1;
for (let i = 1; i <= 9; ++ i) {
    s *= i;
    factorials[i] = s;
}
factorials[0] = 1;
let factorials = {};
let s = 1;
for (let i = 1; i <= 9; ++ i) {
    s *= i;
    factorials[i] = s;
}
factorials[0] = 1;

A single loop from 1 to 9 is sufficient as we are iteratively multiple the next number.

Uppper bound of the Curious Numbers

We don’t need to and we can’t search infinite numbers. One upperbound we can use is 9999999 as 7*9! is less than 9999999.

We then bruteforce all the numbers and sum those curious numbers. The curious number can be determined by the following procedure: converted to string, and split into char array, then sum up the digital factorials, finally comparing the sum with the number.

1
2
3
4
5
6
7
8
9
10
let sum = 0;
for (let i = 3; i <= 9999999; ++ i) {
    let x = String(i).split('').reduce((a, b) => {
        return a + factorials[b];
    }, 0);
    if (x === i) {
        sum += i;
    }
}
console.log(sum);
let sum = 0;
for (let i = 3; i <= 9999999; ++ i) {
    let x = String(i).split('').reduce((a, b) => {
        return a + factorials[b];
    }, 0);
    if (x === i) {
        sum += i;
    }
}
console.log(sum);

The answer is 40730.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
数学题:他们到达A、B两地的中点C地时都会提速20%  一个数的近似值是20万,这个数最大是多少?最小是多少?  图中有多少个长方形  一块正方形的纸板(如图),先剪下宽7厘米的长方形  数学题:9个队员进行单循环制猜丁壳比赛  数学题:有三位登山者要攀登一座荒无人烟的大山。出发时每人只能携带够6天的食物  数学题:一个多位数四舍五入后是1亿,这个数最小是多少?  新网站优化对于一个企业来说到底有多重要  大学生如何在渗透测试行业立足  网站渗透测试中的历程经验记录分析 
评论列表
添加评论