|
1 | | -/* |
2 | | -Factorial digit sum |
| 1 | +/** |
| 2 | + * Problem 20 - Factorial digit sum |
| 3 | + * |
| 4 | + * @see {@link https://projecteuler.net/problem=20} |
| 5 | + * |
| 6 | + * n! means n ×ばつ (n − 1) ×ばつ ... ×ばつ 3 ×ばつ 2 ×ばつ 1 |
| 7 | + * |
| 8 | + * For example, 10! = 10 ×ばつ 9 ×ばつ ... ×ばつ 3 ×ばつかける 2 ×ばつかける 1 =わ 3628800, |
| 9 | + * and the sum of the digits in the number 10! is 3 +たす 6 +たす 2 +たす 8 +たす 8 +たす 0 +たす 0 =わ 27 |
| 10 | + * |
| 11 | + * Find the sum of the digits in the number 100! |
| 12 | + */ |
3 | 13 |
|
4 | | -n! means n ×ばつ (n − 1) ×ばつ ... ×ばつ 3 ×ばつ 2 ×ばつ 1 |
| 14 | +constfactorialDigitSum=function (n =100){ |
5 | 15 |
|
6 | | -For example, 10! = 10 ×ばつ 9 ×ばつ ... ×ばつ 3 ×ばつかける 2 ×ばつかける 1 =わ 3628800, |
7 | | -and the sum of the digits in the number 10! is 3 +たす 6 +たす 2 +たす 8 +たす 8 +たす 0 +たす 0 =わ 27. |
| 16 | +// Consider each digit*10^exp separately, right-to-left ([units, tens, ...]). |
| 17 | +letdigits =[1]; |
8 | 18 |
|
9 | | -Find the sum of the digits in the number 100! |
10 | | -*/ |
| 19 | + for (let x=2; x<=n; x++) { |
| 20 | + let carry = 0; |
| 21 | + for (let exp=0; exp<digits.length; exp++) { |
| 22 | + const prod = digits[exp]*x + carry; |
| 23 | + carry = Math.floor(prod/10); |
| 24 | + digits[exp] = prod % 10; |
| 25 | + } |
| 26 | + while (carry > 0) { |
| 27 | + digits.push(carry%10); |
| 28 | + carry = Math.floor(carry/10); |
| 29 | + } |
| 30 | + } |
11 | 31 |
|
12 | | -const findFactorialDigitSum = (num) => { |
13 | | - let result = 0 |
14 | | - const stringifiedNumber = factorize(num).toLocaleString('fullwide', { useGrouping: false }) |
15 | | - stringifiedNumber.split('').map(num => { result += Number(num) }) |
16 | | - return result |
| 32 | + // (digits are reversed but we only want the sum so it doesn't matter) |
| 33 | + |
| 34 | + return digits.reduce((prev, current) => prev + current, 0) |
17 | 35 | }
|
18 | 36 |
|
19 | | -constfactorize=(num)=>num===0 ? 1 : num*factorize(num-1) |
| 37 | +console.log('Factorial digit sum of 100! :',factorialDigitSum()) |
20 | 38 |
|
21 | | -console.log(findFactorialDigitSum(100)) |
| 39 | +module.exports=factorialDigitSum |
0 commit comments