# Project Euler: #16 - Power digit sum

### **Problem**

2<sup>15</sup> = 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<sup>1000</sup>?

---

### **Problem Description**

The problem is pretty self-explanatory. 2<sup>15</sup> is `32768` and the sum of its digits is `3 + 2 + 7 + 6 + 8 = 26`. So what will be the sum of digits of 2<sup>1000</sup>?

---

### **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 2<sup>53</sup>.**

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**

```javascript
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**](https://github.com/sansk/project-euler-solutions-javascript/tree/main/16)

For [**Hackerrank**](https://www.hackerrank.com/contests/projecteuler/challenges/euler016/problem), 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.**](https://theintrovertcoder.hashnode.dev/series/project-euler)

Thank you!

**Reference:**

* *For more on BigInt, refer to the articles in* [smashing magazine](https://www.smashingmagazine.com/2019/07/essential-guide-javascript-newest-data-type-bigint/) *and* [*MDN*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
