Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 30 additions & 15 deletions Project-Euler/Problem020.js
Original file line number Diff line number Diff line change
@@ -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 }
16 changes: 16 additions & 0 deletions Project-Euler/test/Problem020.test.js
Original file line number Diff line number Diff line change
@@ -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)
})
})