feat(euler): 20 - Factorial digit sum
-
This commit is contained in:
parent
35415ae25e
commit
5795d11620
2 changed files with 32 additions and 1 deletions
|
@ -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] [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] [18 - Maximum path sum I](src/18%20-%20Maximum%20path%20sum%20I.ts)
|
||||||
- [x] [19 - Counting Sundays](src/19%20-%20Counting%20Sundays.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
|
- [ ] 21 - Amicable numbers
|
||||||
- [ ] 22 - Names scores
|
- [ ] 22 - Names scores
|
||||||
- [ ] 23 - Non-abundant sums
|
- [ ] 23 - Non-abundant sums
|
||||||
|
|
31
challenges/euler/src/20 - Factorial digit sum.ts
Normal file
31
challenges/euler/src/20 - Factorial digit sum.ts
Normal file
|
@ -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);
|
Loading…
Reference in a new issue