Skip to content

Commit a9e2661

Browse files
committed
Project Euler : add solution for problem 16 (Power digit sum).
1 parent 7af7a1f commit a9e2661

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Project-Euler/Problem016.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Problem 16 - Power digit sum
3+
*
4+
* @see {@link https://projecteuler.net/problem=16}
5+
*
6+
* 2¹⁵ = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
7+
*
8+
* What is the sum of the digits of the number 2¹⁰⁰⁰ ?
9+
*/
10+
11+
/**
12+
* Returns the power digit sum of n^pow.
13+
*
14+
* @param {number} [n=2]
15+
* @param {number} [pow=1000]
16+
* @returns {number}
17+
*/
18+
const powerDigitSum = function (n = 2, pow = 1000) {
19+
// The idea is to consider each digit (d*10^exp) separately, right-to-left.
20+
// digits = [units, tens, ...]
21+
22+
const digits = [n]
23+
let p = 1
24+
25+
while (++p <= pow) {
26+
let carry = 0
27+
for (let exp = 0; exp < digits.length; exp++) {
28+
const prod = digits[exp] * n + carry
29+
carry = Math.floor(prod / 10)
30+
digits[exp] = prod % 10
31+
}
32+
while (carry > 0) {
33+
digits.push(carry % 10)
34+
carry = Math.floor(carry / 10)
35+
}
36+
}
37+
38+
// (digits are reversed but we only want the sum so it doesn't matter)
39+
40+
return digits.reduce((prev, current) => prev + current, 0)
41+
}
42+
43+
console.log('Power digit sum of 2^1000 :', powerDigitSum())
44+
45+
module.exports = powerDigitSum

0 commit comments

Comments
 (0)