Project Euler – Problem 40

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


class runner
{
	private static int slow_logic(int n){
		String x = "";
		int i = 1;
		while(x.length() <= n){
			x+=i;
			i++;
		}
		return x.charAt(n) - 48;
	}
	private static int fast_logic(int n){
		int n_tens = 0;
		int next_sub = 0, sub = 0;
		do{
			n_tens++;
			sub = next_sub;
			next_sub = next_sub + 9*n_tens*(int)Math.pow(10, (n_tens-1));
		}while(n > next_sub);
		if(n>9)n--;
		n-=sub;

		int r = n%(n_tens);
		int out =  n_tens == 1 ? 0 : (int) Math.pow(10, n_tens-1);
		int d=n/n_tens;
		out = out+d;

		String lazy = ""+out;
		return lazy.charAt(r)-48;
	}

	public static void main (String[] args) throws java.lang.Exception
	{
		long time = System.currentTimeMillis();

		int[] find = {1,10,100,1000,10000,100000,1000000};

		int prod = 1;
		for(int i: find){
			prod *= fast_logic(i);
			//prod *= slow_logic(i);
		}
		System.out.println(prod);

		System.out.println("time: "+(System.currentTimeMillis() - time));
	}
}


Note: Not sure why

next_sub = next_sub + 9*n_tens*(int)Math.pow(10, (n_tens-1));

causes the code to require:
if(n>9)n--;

If you do find out how to remove if(n>9)n--;, please let me know.