diff --git a/challenges/euler/readme.md b/challenges/euler/readme.md index 6ef1d5d..838e4d6 100644 --- a/challenges/euler/readme.md +++ b/challenges/euler/readme.md @@ -31,7 +31,7 @@ The source code can be found in the [src](src) directory. My thoughts about some - [x] [17 - Number letter counts](src/17%20-%20Number%20letter%20counts.ts) - [x] [18 - Maximum path sum I](src/18%20-%20Maximum%20path%20sum%20I.ts) - [x] [19 - Counting Sundays](src/19%20-%20Counting%20Sundays.ts) -- [ ] 20 - Factorial digit sum +- [x] [20 - Factorial digit sum](src/20%20-%20Factorial%20digit%20sum.ts) - [ ] 21 - Amicable numbers - [ ] 22 - Names scores - [ ] 23 - Non-abundant sums diff --git a/challenges/euler/src/20 - Factorial digit sum.ts b/challenges/euler/src/20 - Factorial digit sum.ts new file mode 100644 index 0000000..d2fe723 --- /dev/null +++ b/challenges/euler/src/20 - Factorial digit sum.ts @@ -0,0 +1,31 @@ +// n! means n × (n − 1) × ... × 3 × 2 × 1 +// For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. +// Find the sum of the digits in the number 100! +export = {}; + +/** + * Calculate n! as a BigInt + */ +const factorial = (n: number) => { + if (n < 0) return BigInt(-1); + else if (n === 0) return BigInt(1); + else return BigInt(BigInt(n) * factorial(n - 1)); +}; + +/** + * Find the sum of the digits in a number + */ +const sumOfDigits = (n: number) => { + let sum = 0; + + n.toString() + .split('') + .map(d => parseInt(d)) + .forEach(digit => (sum += digit)); + + return sum; +}; + +// Output +const digitSum = sumOfDigits(factorial(100)); +console.log(digitSum);