Project Euler/16: Difference between revisions
From charlesreid1
No edit summary |
No edit summary |
||
| Line 1: | Line 1: | ||
Project Euler problem 16: https://projecteuler.net/problem=16 | Project Euler problem 16: https://projecteuler.net/problem=16 | ||
Problem 16 asks to find the sum of the digits of <math>2^1000</math>. | Problem 16 asks to find the sum of the digits of <math>2^{1000}</math>. | ||
This is obviously much larger than the capacity of Java's int, <math>2^32</math>, or long, <math>2^64</math>. However, Java's math library has a big integer type built in that allows for arbitrary precision algebra. Solving this problem is as easy as learning how to call it. The number is not as large as it looks - it won't overwhelm a computer to actually compute it. Java computes it in less than a second. | This is obviously much larger than the capacity of Java's int, <math>2^{32}</math>, or long, <math>2^{64}</math>. However, Java's math library has a big integer type built in that allows for arbitrary precision algebra. Solving this problem is as easy as learning how to call it. The number is not as large as it looks - it won't overwhelm a computer to actually compute it. Java computes it in less than a second. | ||
<pre> | <pre> | ||
| Line 11: | Line 11: | ||
user 0m1.166s | user 0m1.166s | ||
sys 0m0.090s | sys 0m0.090s | ||
</pre> | |||
The entire code consists of 2 steps and 8 lines. | |||
The first step is to compute 2^1000, | |||
<pre> | |||
BigInteger n = new BigInteger("2"); | |||
n = n.pow(1000); | |||
</pre> | |||
and the second step is to sum up the digits of this number, | |||
<pre> | |||
char[] p = n.toString().toCharArray(); | |||
int sum = 0; | |||
for(int j = 0; j < p.length; j++ ) { | |||
int z = Character.digit(p[j],10); | |||
sum += z; | |||
} | |||
</pre> | </pre> | ||
Revision as of 02:14, 5 July 2017
Project Euler problem 16: https://projecteuler.net/problem=16
Problem 16 asks to find the sum of the digits of $ 2^{1000} $.
This is obviously much larger than the capacity of Java's int, $ 2^{32} $, or long, $ 2^{64} $. However, Java's math library has a big integer type built in that allows for arbitrary precision algebra. Solving this problem is as easy as learning how to call it. The number is not as large as it looks - it won't overwhelm a computer to actually compute it. Java computes it in less than a second.
$ time javac BigNum.java && java BigNum real 0m0.630s user 0m1.166s sys 0m0.090s
The entire code consists of 2 steps and 8 lines.
The first step is to compute 2^1000,
BigInteger n = new BigInteger("2");
n = n.pow(1000);
and the second step is to sum up the digits of this number,
char[] p = n.toString().toCharArray();
int sum = 0;
for(int j = 0; j < p.length; j++ ) {
int z = Character.digit(p[j],10);
sum += z;
}