Project Euler Problem 40: Champernowne’s Constant¶
The source code for this problem can be found here.
Problem Statement¶
An irrational decimal fraction is created by concatenating the positive integers:
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.
Solution Discussion¶
Explicitly building this decimal representation is not clever but will work, a \(1000000\) digit number is not large in the scheme of things.
Use Python to build the fractional part as a string of decimal digits and then simply index into the relevant points to extract each \(d_i\) needed. Finally, multiply these values to compute the answer.
Solution Implementation¶
from functools import reduce
from operator import mul
def solve():
""" Compute the answer to Project Euler's problem #40 """
upper_limit = 200000 # large enough s.t. the total string length exceeds the highest index
fractional_string = "".join(["{}".format(i + 1) for i in range(upper_limit)]) # build the string representation
# Extract the relevant d_i values
indices = [1, 10, 100, 1000, 10000, 100000, 1000000]
digits = [fractional_string[i - 1] for i in indices] # Python using 0-based indices
# Multiply each d_i together to get the answer
answer = reduce(mul, map(int, digits))
return answer
expected_answer = 210
-
solutions.problem40.
solve
()¶ Compute the answer to Project Euler’s problem #40