Euler Solution 52

From ProgSoc Wiki

Jump to: navigation, search

Solutions for Problem 52

Find the smallest positive integer n such that 1n, 2n, 3n, 4n, 5n and 6n all contain exactly the same digits (in any order).

Haskell by SanguineV

Runtime: 309.28 ms (on aglaope)

{- Given a list of integers return true if they all contain the same digits.
 - Note: this is a hack, assumes the first element contains all digits we want
 - and doesn't check for repeated digits. It is adaquate for this problem based on
 - the assumption that the first element will contain all the digits. -}
allDigs :: [Integer] -> Bool
allDigs (x:xs) = foldl inner True xs
    inner :: Bool -> Integer -> Bool
    inner False _ = False
    inner _ n = foldl (\a c -> a && elem c (show n)) True (show x)

{- Start at 1 and increment through the integers. For each n, create a list of n
 - multiplied by 6,5,4,3,2 and 1 (in reverse order to aid the assumption used above).
 - Then filter with the "allDigs" function. Take the first such list and print the
 - last element (n * 1). -}
main = print (last (head (filter allDigs (map (\z -> map (\x -> x * z) [6,5..1]) [1..]))))

Python by Althalus

Runtime: 1.05 seconds

def isPerm(n1,n2):
        n1,n2 = str(n1),str(n2)
        if len(n1) != len(n2): return False
        return all(n1.count(c) == n2.count(c) for c in n1)

x = 1
while True:
        if isPerm(x,6*x) and isPerm(x,5*x) and isPerm(x,4*x) and isPerm(x,3*x) and isPerm(x,2*x):
                print x
Personal tools