Project Euler: #16 - Power digit sum

Project Euler: #16 - Power digit sum

Problem

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?


Problem Description

The problem is pretty self-explanatory. 215 is 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. So what will be the sum of digits of 21000?


Approach

While handling bigger power, the resulting large number can not be handled by Javascript.

One approach is to use column multiplication using arrays.

Another approach, which I have opted for is to use BigInt with 2 ** n, where n is the power.

BigInt is a built-in object in JavaScript that represents whole numbers larger than 253.

Note that, We could have used Math.pow() but BigInt can not be used with a Math object as they expect Number as arguments. And BigInt can't accurately convert to a Number. So we settle with 2 ** n.

Note: Please note that the solution provided is only for learning purposes. Once you understand the problem, please try it on your own before referring to my solution below.


Solution

const digitSum = n => {
    let power = 2n ** BigInt(n);
    // Convert BigInt into a String by concatenating with an empty string.
    let strNum = '' + power; 

    return strNum.split('').map(Number).reduce((acc, curr) => acc + curr, 0);
}

console.log(digitSum(1000));

You can find my solution on GitHub 16

For Hackerrank, the above solution works fine for all 10 test cases.

If you have any feedback, please leave it below.

If you have any suggestions to improve my code or another way to approach this problem, leave it in the comment.

For the other Project Euler Solutions, please follow the series Project Euler Solutions in JS.

Thank you!

Reference: