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
    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))

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:
Personal tools