chore: Merge pull request #747 from lvlte/ProjectEuler/020

Project Euler - Problem 20 (fix + test)
This commit is contained in:
Rak Laptudirm
2021-10-08 17:36:48 +05:30
committed by GitHub
2 changed files with 46 additions and 15 deletions

View File

@ -1,21 +1,36 @@
/*
Factorial digit sum
/**
* Problem 20 - Factorial digit sum
*
* @see {@link https://projecteuler.net/problem=20}
*
* 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!
*/
n! means n × (n 1) × ... × 3 × 2 × 1
const factorialDigitSum = (n = 100) => {
// Consider each digit*10^exp separately, right-to-left ([units, tens, ...]).
const digits = [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.
for (let x = 2; x <= n; x++) {
let carry = 0
for (let exp = 0; exp < digits.length; exp++) {
const prod = digits[exp] * x + carry
carry = Math.floor(prod / 10)
digits[exp] = prod % 10
}
while (carry > 0) {
digits.push(carry % 10)
carry = Math.floor(carry / 10)
}
}
Find the sum of the digits in the number 100!
*/
// (digits are reversed but we only want the sum so it doesn't matter)
const findFactorialDigitSum = (num) => {
let result = 0
const stringifiedNumber = factorize(num).toLocaleString('fullwide', { useGrouping: false })
stringifiedNumber.split('').map(num => { result += Number(num) })
return result
return digits.reduce((prev, current) => prev + current, 0)
}
const factorize = (num) => num === 0 ? 1 : num * factorize(num - 1)
console.log(findFactorialDigitSum(100))
export { factorialDigitSum }

View File

@ -0,0 +1,16 @@
import { factorialDigitSum } from '../Problem020'
describe('Check Problem 20 - Factorial digit sum', () => {
it('Factorial digit sum of 10!', () => {
expect(factorialDigitSum(10)).toBe(27)
})
it('Factorial digit sum of 100!', () => {
expect(factorialDigitSum()).toBe(648)
expect(factorialDigitSum(100)).toBe(648)
})
it('Factorial digit sum of 1000!', () => {
expect(factorialDigitSum(1000)).toBe(10539)
})
})