Power Digit Sum: What is the sum of the digits of the number 2^1

  • 时间:2020-09-10 12:45:51
  • 分类:网络文摘
  • 阅读:123 次

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 2
1000?

You probably can compute the direct value of 2^1000. For example, in Python, you can obtain value of (2**1000) and convert it to string. In Java, you can use BigInteger to compute the value of two to the power of 1000.

We can use an array, or hash map to store the digits of any big number. Each time we multiple each position (the values) of the array/hashmap by two, then we need to start from the ‘One’ position to carry over the digits.

The following Javascript code first computes the value of 21000 (values store in a dictionary), then compute the sum of all the digits using reduce() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
let arr = {
    0: 1
};
 
for (let i = 1; i <= 1000; ++i) {
    // multiple each digit by two
    Object.keys(arr).map(x => {
        arr[x] *= 2;
    });
    let c = Math.floor(arr[0] / 10);
    let j = 1;
    arr[0] %= 10;
    // highest position
    const maxKey = Math.max(...Object.keys(arr));
    while ((c > 0) || (j <= maxKey)) {
        if (typeof arr[j] === 'undefined') {
            arr[j] = c;
        } else {
            arr[j] = arr[j] + c;
        }
        c = Math.floor(arr[j] / 10);
        arr[j] %= 10;
        j ++;
    }
}
 
// sum up all the digits
console.log(Object.values(arr).reduce((a, b) => a + b));
let arr = {
    0: 1
};

for (let i = 1; i <= 1000; ++i) {
    // multiple each digit by two
    Object.keys(arr).map(x => {
        arr[x] *= 2;
    });
    let c = Math.floor(arr[0] / 10);
    let j = 1;
    arr[0] %= 10;
    // highest position
    const maxKey = Math.max(...Object.keys(arr));
    while ((c > 0) || (j <= maxKey)) {
        if (typeof arr[j] === 'undefined') {
            arr[j] = c;
        } else {
            arr[j] = arr[j] + c;
        }
        c = Math.floor(arr[j] / 10);
        arr[j] %= 10;
        j ++;
    }
}

// sum up all the digits
console.log(Object.values(arr).reduce((a, b) => a + b));

The answer is 1366.

Based on the same algorithm, we can solve another math puzzle: Compute Factorial Digit Sum: Find the sum of the digits in the number 100!

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
春季喝蜂蜜功效胜补品抗过敏润肺止咳  这十种食用方法让蜂蜜营养又健康  婴幼儿等四类人群不宜食用蜂蜜  教你这七招快速辨别蜂蜜的真假  舌尖上的中国之虾子面背后的故事  豆浆和什么食物一起搭配吃更健康  家庭制作豆浆的步骤及豆浆搭配宜忌  怎么喝啤酒健康养生及饮用啤酒禁忌  饮食安全:警惕9类食物含强致癌物质  造成牙龈萎缩的原因及食疗预防牙龈萎缩 
评论列表
添加评论