Problem 40: Champernowne’s constant is about a constant whose digits are made up of the natural numbers.
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 $d_n$ represents the nth 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}$
Here I found it helpful to construct a sensible generator for the digits such that the counting becomes easy.
def generate_digits() -> Iterator[str]:
for number in itertools.count(1):
s = str(number)
yield from s
As usual, write a test to make sure that it works properly.
def test_generate_digits() -> None:
s = "".join(itertools.islice(generate_digits(), 20))
assert s == "12345678910111213141"
Then the solution is rather straightforward, just go through all the digits and take out the ones we are interested in.
def solution() -> int:
result = 1
power_of_ten = 1
for i, digit in enumerate(generate_digits(), start=1):
if i == power_of_ten:
result *= int(digit)
power_of_ten *= 10
if power_of_ten > 1_000_000:
break
return result
This produces the result in 93 ms.