Project Euler: Problem 40 – Champernowne’s constant

Problem 40:

An irrational decimal fraction is created by concatenating the positive integers:
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 x d10 x d100 x d1000 x d10000 x d100000 x d1000000


While overkill on the number of digits, I figured (at the time) it would be easiest to just append the numbers 1 – 1 million in a String (although I could’ve checked the length after each append, I didn’t think it was worth it, unless I ran into a buffer overflow error of some sort, but I didn’t). Then it was just a matter of multiplying the specified index digits together.

long answer = -1;

StringBuilder sb = new StringBuilder();
int i = 1;
while(sb.length() < 1000000) {
i = 1;
long val = Integer.parseInt(""+sb.charAt(i-1));

while(i <= 1000000) {
   val *= Integer.parseInt(""+sb.charAt(i-1));
answer = val;

System.out.println("Answer: "+answer);