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 |
Python1
2#!/usr/bin/env python
print(sum(int(digit) for digit in str(2**1000)))
Ruby1
2#!/usr/bin/env ruby
puts (2**1000).to_s.each_char.inject(0) {|s,v| s+v.to_i}
Haskell1
2
3
4
5
6
7sumDigits :: 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
Java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22import 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);
}
}
Mathematica1
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]]