# Euler Problem 40

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 d10 d100 d1000 d10000 d100000 d1000000﻿

Is it just me, or does this problem have nothing to do with fractions? I started by building strings, which worked fine until you get to the last digit — then Java slows way down, probably due to massive string concatenations. Bad idea. So instead I built a counter with an internal while loop, which stopped each time it got to the needed digit. The trick is to test for character variance because there’s no guarantee that the cumulative length of each milestone ends at a round number.

import java.util.*;

public class Euler40
{
public static void main(String[] args)
{
System.out.format(“Problem 40:\n”);
Euler40 e = new Euler40();
System.out.format(“Answer = %s\n”, e.Problem());
}
public String Problem ()
{
ArrayList<Integer> D = new ArrayList<Integer>();
int i = 1, len = 1, var = 0, product = 1;
for (int d = 1; d <= 1000000; d *= 10)
{
while (len < d)
{
len += Integer.toString(i++).length();
var = len – d;
}
int t = (int)Integer.toString(i).charAt(var)-48;