Euler Problem 40

An irrational decimal fraction is created by concatenating the positive integers:

0.123456789101112131415161718192021…

It can be seen that the 12^(th) digit of the fractional part is 1.

If d_(n) represents the n^(th) digit of the fractional part, find the value of the following expression.

d_(1) × d_(10) × d_(100) × d_(1000) × d_(10000) × d_(100000) × d_(1000000

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;
        D.add(i);
        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;
            D.add(t);
            product *= t;
        }
        System.out.print(D+”\n”);
        return String.valueOf(product);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s