Project Euler

A Taste of Number Theory

Problem 40: Champernowne's Constant

An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021...
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

The Catch

How to quickly construct the irrational number by concatenating incremented-positive-integers.

The Light

Use Java's StringBuilder class to concatenate incremented-positive-integers. Since there is no actual calculation involved, the construction should be very quick. Once the irrational number is constructed, pick out requested indexed-digits and find their product.

The Code

public class Problem40
  public static void main(String[] args)
    StringBuilder sb = new StringBuilder(1000000);
    int i = 1;
    int result = 1;

    while(i <= 1000000)
      sb = sb.append(i++);
    String s = sb.toString();

    for(i = 1; i <= 1000000; i *= 10)
      result *= Character.getNumericValue(s.charAt(i - 1));
    System.out.println("Result = " + result);