JavaScript Implementation of Problem 16

View source code here on GitHub!

p0016()

Project Euler Problem 16

Problem: 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2**1000?

Returns:

number --

 1/**
 2 * Project Euler Problem 16
 3 *
 4 * Problem:
 5 * 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
 6 *
 7 * What is the sum of the digits of the number 2**1000?
 8 * @return {number}
 9 */
10exports.p0016 = function() {
11    const ten13 = 10000000000000;
12    const numbers = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13    for (let i = 0; i < 1000; i++) {
14        for (let j = 0; j < numbers.length; j++) {
15            numbers[j] *= 2;
16        }
17        for (let j = 0; j < numbers.length - 1; j++) {
18            if (numbers[j] > ten13) {
19                numbers[j + 1] += 0 | (numbers[j] / ten13);
20                numbers[j] %= ten13;
21            }
22        }
23    }
24    let answer = 0;
25    let power = 1;
26    while (power < ten13) {
27        for (let j = 0; j < numbers.length; j++) {
28            answer += 0 | ((numbers[j] / power) % 10);
29        }
30        power *= 10;
31    }
32    return answer;
33};

Tags: large-numbers, digit-sum, power