Project Euler Problem 40 Solution

Question

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}

Haskell

champernowne :: String
champernowne = foldr (\x acc -> (show x) ++ acc) "" [1..]

main :: IO ()
main = print $ product [read [champernowne !! (n - 1)] | n <- [10^x | x <- [0..6]]]
$ ghc -O2 -o champernowne champernowne.hs
$ time ./champernowne
real   0m0.060s
user   0m0.051s
sys    0m0.009s

Python

#!/usr/bin/env python
d = [int(digit) for digit in ''.join((str(digit) for digit in range(1, 10000001)))]
print(d[0] * d[9] * d[99] * d[999] * d[9999] * d[99999] * d[999999])
$ time python3 irrational-part.py
real   0m19.793s
user   0m19.351s
sys    0m0.441s

Ruby

#!/usr/bin/env ruby
s = ('1'..'1000000').to_a.join ''
puts (0..6).map { |i|
  s[(10**i)-1].to_i
}.reduce(1, :*)
$ time ruby irrational-part.rb
real   0m0.510s
user   0m0.487s
sys    0m0.024s