Back to Project Euler

Previous Problem Next Problem

Problem 40: Champernowne's Constant

An irrational decimal fraction is created by concatenating the positive integers: \[0.12345678910{\color{red}\mathbf 1}112131415161718192021\cdots\]

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 \times d_{10} \times d_{100} \times d_{1000} \times d_{10000} \times d_{100000} \times d_{1000000}\]

Solution

For every \(c\), there are \(9 \cdot 10^{c-1}\) numbers with \(c\) digits, so these numbers take up a total of \(9c \cdot 10^{c-1}\) digits in Champernowne's constant. The \(k\)-th number with \(c\) digits is \(10^{c-1} + k - 1\). Let \(d(c,n)\) be the \(n\)th digit of the part of the decimal beginning with \(10^{c-1}\), and let \(f(i,m)\) be the \(i\)th digit of the number \(m\). Then \(d_n = d(1,n)\), and

\[ d(c,n) = \begin{cases} d(c+1,n-9c\cdot 10^{c-1}) & \text{if } 9c\cdot 10^{c-1} < n \\ f\left(1 + ((n-1) \mod c), 10^{c-1} + \left\lfloor \frac {n-1}c \right\rfloor\right) & \text{if } 9c\cdot 10^{c-1} \geq n \end{cases} \]

Python Code

def p40():
	res = 1
	for x in range(7):
		c, n = 1, 10 ** x
		while True:
			if 9 * c * 10 ** (c-1) < n:
				n -= 9 * c * 10 ** (c-1)
				c += 1
			else:
				k = 10 ** (c-1) + (n-1) // c
				res *= int(str(k)[(n-1)%c])
				break
	return res

Previous Problem Next Problem

Back to Project Euler