diff --git a/Project-Euler/Problem020.js b/Project-Euler/Problem020.js index fc92df4f9c..256a4fb5de 100644 --- a/Project-Euler/Problem020.js +++ b/Project-Euler/Problem020.js @@ -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 } diff --git a/Project-Euler/test/Problem020.test.js b/Project-Euler/test/Problem020.test.js new file mode 100644 index 0000000000..9a4c31e186 --- /dev/null +++ b/Project-Euler/test/Problem020.test.js @@ -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) + }) +})