Project Euler Problem 40 Solution

Question

An irrational decimal fraction is created by concatenating the positive integers:

0.123456789101112131415161718192021...\displaystyle 0.123456789101112131415161718192021...

It can be seen that the 12th digit of the fractional part is 1.

If dnd_n represents the nth digit of the fractional part, find the value of the following expression.

d1×d10×d100×d1000×d10000×d100000×d1000000\displaystyle 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.079s
user   0m0.064s
sys    0m0.012s

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   0m15.868s
user   0m15.324s
sys    0m0.428s

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.494s
user   0m0.460s
sys    0m0.016s