Project-Euler-016

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}$?

Answer

1
1366

Python

1
2
#!/usr/bin/env python
print(sum(int(digit) for digit in str(2**1000)))


Ruby

1
2
#!/usr/bin/env ruby
puts (2**1000).to_s.each_char.inject(0) {|s,v| s+v.to_i}


Haskell

1
2
3
4
5
6
7
sumDigits ::  Integer -> Integer
sumDigits n = sumDigits' n 0
where sumDigits' 0 acc = acc
sumDigits' n acc = sumDigits' (div n 10) (acc + (mod n 10))

main :: IO ()
main = print $ sumDigits $ 2^1000


Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.math.BigInteger;


public final class p016 implements EulerSolution {

public static void main(String[] args) {
System.out.println(new p016().run());
}


/*
* We implement this solution in a straightforward way with help from BigInteger.
*/
public String run() {
String temp = BigInteger.ONE.shiftLeft(1000).toString();
int sum = 0;
for (int i = 0; i < temp.length(); i++)
sum += temp.charAt(i) - '0';
return Integer.toString(sum);
}

}


Mathematica

1
2
3
4
5
(* 
* We implement this solution in a straightforward way thanks to
* Mathematica's built-in functions and arbitrary precision integer type.
*)
Total[IntegerDigits[2^1000]]

文章作者: Monad Kai
文章链接: onlookerliu.github.io/2018/03/11/Project-Euler-016/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Code@浮生记
支付宝打赏
微信打赏