Euler Solution 40

From ProgSoc Wiki

Jump to: navigation, search

Solutions for Problem 40

Given the number of the form: 0.123456789101213141516171819202122... with the function d such that d(n) is the nth digit after the dot. Compute d(1) * d(100) * d(1000) * d(10000) * d(100000) * d(1000000)

Haskell by SanguineV

Runtime: 132.5ms

{- Ok I am getting tired of writing my own append/concat and basic conversion functions
 - so import "concat" from List and "digitToInt" from Char. -}
import Data.List
import Data.Char

{- Create a lazy list of characters that correspond to the natural numbers concatonated
 - after a dot. -}
digits :: [Char]
digits = "." ++ digs
  where
    digs = concat (map show [1..])

{- Now the easy part, given a list of indices, map the character at each index to an
 - integer, then fold these together with multiplication.
 - NOTE: as usual, broken lines to simplify reading, one line to compile. -}
main = print (foldl (\x y -> x * y) 1 
         (map (\z -> digitToInt (digits !! z))
             [1,10,100,1000,10000,100000,1000000]))

It looks easy when it is done, but the creation of the lazy string is non-trivial, some operations that seem obvious (such as folding) cause the entire string (list) to be created and will cause segmentation faults in the "hugs" interpreter!

Python by Althalus

Runtime: 42 ms

number = '0'    #string is zero indexed. Sticking a digit outside the sequence
                # puts the first digit at 1. (don't need to adjust dn)

#Generate our list of numbers.
#The fact that it is an irrational decimal seems to me to have no relevance to actually solving the problem...
n = 1
while len(number) <= 100000:
    number+=str(n)
    n+=1
print(int(number[1])*int(number[10])*int(number[100])*int(number[1000])*int(number[10000])*int(number[100000]))
Personal tools