Difference between revisions of "Euler problems/71 to 80"

From HaskellWiki
Jump to navigation Jump to search
Line 4: Line 4:
 
Solution:
 
Solution:
 
<haskell>
 
<haskell>
  +
-- http://mathworld.wolfram.com/FareySequence.html
import Data.Ratio (Ratio, (%), numerator)
 
  +
import Data.Ratio ((%), numerator,denominator)
 
  +
fareySeq a b
fractions :: [Ratio Integer]
 
  +
|da2<=10^6=fareySeq a1 b
fractions =
 
[f |
+
|otherwise=na
  +
where
d <- [1..1000000],
 
  +
na=numerator a
let n = (d * 3) `div` 7,
 
let f = n%d,
+
nb=numerator b
f /= 3%7
+
da=denominator a
  +
db=denominator b
]
 
  +
a1=(na+nb)%(da+db)
 
  +
da2=denominator a1
problem_71 :: Integer
 
problem_71 = numerator $ maximum $ fractions
+
problem_71=fareySeq (0%1) (3%7)
 
</haskell>
 
</haskell>
   
Line 25: Line 25:
   
 
Using the [http://mathworld.wolfram.com/FareySequence.html Farey Sequence] method, the solution is the sum of phi (n) from 1 to 1000000.
 
Using the [http://mathworld.wolfram.com/FareySequence.html Farey Sequence] method, the solution is the sum of phi (n) from 1 to 1000000.
 
See problem 69 for phi function
 
 
 
<haskell>
 
<haskell>
  +
groups=1000
problem_72 = sum [phi x|x <- [1..1000000]]
 
  +
eulerTotient n = product (map (\(p,i) -> p^(i-1) * (p-1)) factors)
  +
where factors = fstfac n
  +
fstfac x = [(head a ,length a)|a<-group$primeFactors x]
  +
p72 n= sum [eulerTotient x|x <- [groups*n+1..groups*(n+1)]]
  +
problem_72 = sum [p72 x|x <- [0..999]]
 
</haskell>
 
</haskell>
   
Line 37: Line 39:
 
Solution:
 
Solution:
 
<haskell>
 
<haskell>
import Data.Ratio (Ratio, (%), numerator, denominator)
+
import Data.Array
  +
twix k = crude k - fd2 - sum [ar!(k `div` m) | m <- [3 .. k `div` 5], odd m]
 
median :: Ratio Int -> Ratio Int -> Ratio Int
 
median a b = ((numerator a) + (numerator b)) % ((denominator a) + (denominator b))
 
 
count :: Ratio Int -> Ratio Int -> Int
 
count a b
 
| d > 10000 = 1
 
| otherwise = count a m + count m b
 
 
where
 
where
m = median a b
+
fd2 = crude (k `div` 2)
d = denominator m
+
ar = array (5,k `div` 3) $
  +
((5,1):[(j, crude j - sum [ar!(j `div` m) | m <- [2 .. j `div` 5]])
 
  +
| j <- [6 .. k `div` 3]])
problem_73 :: Int
 
  +
crude j =
problem_73 = (count (1%3) (1%2)) - 1
 
  +
m*(3*m+r-2) + s
  +
where
  +
(m,r) = j `divMod` 6
  +
s = case r of
  +
5 -> 1
  +
_ -> 0
  +
  +
problem_73 = twix 10000
 
</haskell>
 
</haskell>
   
Line 59: Line 62:
 
Solution:
 
Solution:
 
<haskell>
 
<haskell>
import Data.Array (Array, array, (!), elems)
 
import Data.Char (ord)
 
import Data.List (foldl1')
 
import Prelude hiding (cycle)
 
 
fact :: Integer -> Integer
 
fact 0 = 1
 
fact n = foldl1' (*) [1..n]
 
 
factorDigits :: Array Integer Integer
 
factorDigits =
 
array (0,2177281)
 
[(x,n)|
 
x <- [0..2177281],
 
let n = sum $
 
map (\y -> fact (toInteger $ ord y - 48)) $
 
show x
 
]
 
 
cycle :: Integer -> Integer
 
cycle 145 = 1
 
cycle 169 = 3
 
cycle 363601 = 3
 
cycle 1454 = 3
 
cycle 871 = 2
 
cycle 45361 = 2
 
cycle 872 = 2
 
cycle 45362 = 2
 
cycle _ = 0
 
 
isChainLength :: Integer -> Integer -> Bool
 
isChainLength len n
 
| len < 0 = False
 
| t = isChainLength (len-1) n'
 
| otherwise = (len - c) == 0
 
where
 
c = cycle n
 
t = c == 0
 
n' = factorDigits ! n
 
 
-- | strict version of the maximum function
 
maximum' :: (Ord a) => [a] -> a
 
maximum' [] = undefined
 
maximum' [x] = x
 
maximum' (a:b:xs) = let m = max a b in m `seq` maximum' (m : xs)
 
 
problem_74 :: Int
 
problem_74 =
 
length $ filter
 
(\(_,b) -> isChainLength 59 b) $
 
zip ([0..] :: [Integer]) $
 
take 1000000 $ elems factorDigits
 
</haskell>
 
 
Slightly faster solution :
 
<haskell>{-# OPTIONS_GHC -fbang-patterns #-}
 
 
import Data.List
 
import Data.List
import Data.Array
 
 
 
explode 0 = []
 
explode 0 = []
 
explode n = n `mod` 10 : explode (n `quot` 10)
 
explode n = n `mod` 10 : explode (n `quot` 10)
  +
 
  +
chain 2 = 1
count :: (a -> Bool) -> [a] -> Int
 
count pred xs = lgo 0 xs
+
chain 1 = 1
where lgo !c [] = c
+
chain 145 = 1
  +
chain 40585 = 1
lgo !c (y:ys) | pred y = lgo (c + 1) ys
 
  +
chain 169 = 3
| otherwise = lgo c ys
 
  +
chain 363601 = 3
 
  +
chain 1454 = 3
known = [([1,2,145,40585],1),([871,45361,872,45362],2),([169,363601,1454],3)]
 
  +
chain 871 = 2
mChain = array (1,1000000) $ (concat $ expand known)
 
  +
chain 45361 = 2
++ [(x, n)|x<-[3..1000000]
 
  +
chain 872 = 2
, not $ x `elem` concat (map fst known)
 
  +
chain 45362 = 2
, let n = 1 + chain (sumFactDigits x)]
 
  +
chain x = 1 + chain (sumFactDigits x)
where expand [] = []
 
  +
makeIncreas 1 minnum = [[a]|a<-[minnum..9]]
expand ((xs,len):xxs) = map (flip (,) len) xs : expand xxs
 
  +
makeIncreas digits minnum = [a:b|a<-[minnum ..9],b<-makeIncreas (digits-1) a]
chain x | x <= 1000000 = mChain ! x
 
  +
p74=
| otherwise = 1 + chain (sumFactDigits x)
 
  +
sum[div p6 $countNum a|
 
  +
a<-tail$makeIncreas 6 1,
  +
let k=digitToN a,
  +
chain k==60
  +
]
  +
where
  +
p6=facts!! 6
 
sumFactDigits = foldl' (\a b -> a + facts !! b) 0 . explode
 
sumFactDigits = foldl' (\a b -> a + facts !! b) 0 . explode
  +
factorial n = if n == 0 then 1 else n * factorial (n - 1)
  +
digitToN = foldl' (\a b -> 10*a + b) 0 .dropWhile (==0)
 
facts = scanl (*) 1 [1..9]
 
facts = scanl (*) 1 [1..9]
  +
countNum xs=ys
 
  +
where
problem_74 = count (== 60) $ elems mChain</haskell>
 
  +
ys=product$map (factorial.length)$group xs
 
  +
problem_74= length[k|k<-[1..9999],chain k==60]+p74
  +
test = print $ [a|a<-tail$makeIncreas 6 0,let k=digitToN a,chain k==60]
  +
</haskell>
 
== [http://projecteuler.net/index.php?section=view&id=75 Problem 75] ==
 
== [http://projecteuler.net/index.php?section=view&id=75 Problem 75] ==
 
Find the number of different lengths of wire can that can form a right angle triangle in only one way.
 
Find the number of different lengths of wire can that can form a right angle triangle in only one way.
Line 167: Line 123:
   
 
Solution:
 
Solution:
 
Calculated using Euler's pentagonal formula and a list for memoization.
 
<haskell>
 
partitions =
 
1 : [sum
 
[s * partitions !! p|
 
(s,p) <- zip signs $ parts n
 
]|
 
n <- [1..]]
 
where
 
signs = cycle [1,1,(-1),(-1)]
 
suite = map penta $ concat [[n,(-n)]|n <- [1..]]
 
penta n = n*(3*n - 1) `div` 2
 
parts n = takeWhile (>= 0) [n-x| x <- suite]
 
 
problem_76 = partitions !! 100 - 1
 
</haskell>
 
   
 
Here is a simpler solution: For each n, we create the list of the number of partitions of n
 
Here is a simpler solution: For each n, we create the list of the number of partitions of n
Line 189: Line 128:
 
<haskell>
 
<haskell>
 
build x = (map sum (zipWith drop [0..] x) ++ [1]) : x
 
build x = (map sum (zipWith drop [0..] x) ++ [1]) : x
problem_76' = (sum $ head $ iterate build [] !! 100) - 1
+
problem_76 = (sum $ head $ iterate build [] !! 100) - 1
 
</haskell>
 
</haskell>
   
Line 199: Line 138:
 
Brute force but still finds the solution in less than one second.
 
Brute force but still finds the solution in less than one second.
 
<haskell>
 
<haskell>
  +
counter = foldl (\without p ->
combinations acc 0 _ = [acc]
 
  +
let (poor,rich) = splitAt p without
combinations acc _ [] = []
 
  +
with = poor ++
combinations acc value prim@(x:xs) =
 
  +
zipWith (+) with rich
combinations (acc ++ [x]) value' prim' ++ combinations acc value xs
 
  +
in with
where
 
value' = value - x
+
) (1 : repeat 0)
  +
prim' = dropWhile (>value') prim
 
  +
problem_77 =
 
  +
find ((>5000) . (ways !!)) $ [1..]
problem_77 :: Integer
 
problem_77 = head $ filter f [1..]
 
 
where
 
where
f n = (length $ combinations [] n $ takeWhile (<n) primes) > 5000
+
ways = counter $ take 100 primes
 
</haskell>
 
</haskell>
   

Revision as of 07:51, 20 January 2008

Problem 71

Listing reduced proper fractions in ascending order of size.

Solution:

-- http://mathworld.wolfram.com/FareySequence.html 
import Data.Ratio ((%), numerator,denominator)
fareySeq a b
    |da2<=10^6=fareySeq a1 b
    |otherwise=na
    where
    na=numerator a
    nb=numerator b
    da=denominator a
    db=denominator b
    a1=(na+nb)%(da+db)
    da2=denominator a1
problem_71=fareySeq (0%1) (3%7)

Problem 72

How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000?

Solution:

Using the Farey Sequence method, the solution is the sum of phi (n) from 1 to 1000000.

groups=1000
eulerTotient n = product (map (\(p,i) -> p^(i-1) * (p-1)) factors)
    where factors = fstfac n
fstfac x = [(head a ,length a)|a<-group$primeFactors x] 
p72 n= sum [eulerTotient x|x <- [groups*n+1..groups*(n+1)]]
problem_72 = sum [p72 x|x <- [0..999]]

Problem 73

How many fractions lie between 1/3 and 1/2 in a sorted set of reduced proper fractions?

Solution:

import Data.Array
twix k = crude k - fd2 - sum [ar!(k `div` m) | m <- [3 .. k `div` 5], odd m]
    where
    fd2 = crude (k `div` 2)
    ar = array (5,k `div` 3) $
          ((5,1):[(j, crude j - sum [ar!(j `div` m) | m <- [2 .. j `div` 5]])
                      | j <- [6 .. k `div` 3]])
    crude j = 
        m*(3*m+r-2) + s
        where
            (m,r) = j `divMod` 6
            s = case r of
                  5 -> 1
                  _ -> 0
 
problem_73 =  twix 10000

Problem 74

Determine the number of factorial chains that contain exactly sixty non-repeating terms.

Solution:

import Data.List
explode 0 = []
explode n = n `mod` 10 : explode (n `quot` 10)
 
chain 2    = 1
chain 1    = 1
chain 145    = 1
chain 40585    = 1
chain 169    = 3
chain 363601 = 3
chain 1454   = 3
chain 871    = 2
chain 45361  = 2
chain 872    = 2
chain 45362  = 2
chain x = 1 + chain (sumFactDigits x)
makeIncreas 1 minnum  = [[a]|a<-[minnum..9]]
makeIncreas digits minnum  = [a:b|a<-[minnum ..9],b<-makeIncreas (digits-1) a]
p74=
    sum[div p6 $countNum a|
    a<-tail$makeIncreas  6 1,
    let k=digitToN a,
    chain k==60
    ]
    where
    p6=facts!! 6
sumFactDigits = foldl' (\a b -> a + facts !! b) 0 . explode
factorial n = if n == 0 then 1 else n * factorial (n - 1)
digitToN = foldl' (\a b -> 10*a + b) 0 .dropWhile (==0)
facts = scanl (*) 1 [1..9]
countNum xs=ys
    where
    ys=product$map (factorial.length)$group xs 
problem_74= length[k|k<-[1..9999],chain k==60]+p74
test = print $ [a|a<-tail$makeIncreas 6 0,let k=digitToN a,chain k==60]

Problem 75

Find the number of different lengths of wire can that can form a right angle triangle in only one way.

Solution: This is only slightly harder than problem 39. The search condition is simpler but the search space is larger.

problem_75 = 
    length . filter ((== 1) . length) $ group perims
    where  perims = sort [scale*p | p <- pTriples, scale <- [1..10^6 `div` p]]
           pTriples = [p |
                       n <- [1..1000],
                       m <- [n+1..1000],
                       even n || even m,
                       gcd n m == 1,
                       let a = m^2 - n^2,
                       let b = 2*m*n,
                       let c = m^2 + n^2,
                       let p = a + b + c,
                       p <= 10^6]

Problem 76

How many different ways can one hundred be written as a sum of at least two positive integers?

Solution:

Here is a simpler solution: For each n, we create the list of the number of partitions of n whose lowest number is i, for i=1..n. We build up the list of these lists for n=0..100.

build x = (map sum (zipWith drop [0..] x) ++ [1]) : x
problem_76 = (sum $ head $ iterate build [] !! 100) - 1

Problem 77

What is the first value which can be written as the sum of primes in over five thousand different ways?

Solution:

Brute force but still finds the solution in less than one second.

counter = foldl (\without p ->
                     let (poor,rich) = splitAt p without
                         with = poor ++ 
                                zipWith (+) with rich
                     in with
                ) (1 : repeat 0)
 
problem_77 =  
    find ((>5000) . (ways !!)) $ [1..]
    where
    ways = counter $ take 100 primes

Problem 78

Investigating the number of ways in which coins can be separated into piles.

Solution:

Same as problem 76 but using array instead of lists to speedup things.

import Data.Array

partitions :: Array Int Integer
partitions = 
    array (0,1000000) $ 
    (0,1) : 
    [(n,sum [s * partitions ! p|
    (s,p) <- zip signs $ parts n])|
    n <- [1..1000000]]
    where
        signs = cycle [1,1,(-1),(-1)]
        suite = map penta $ concat [[n,(-n)]|n <- [1..]]
        penta n = n*(3*n - 1) `div` 2
        parts n = takeWhile (>= 0) [n-x| x <- suite]

problem_78 :: Int
problem_78 = 
    head $ filter (\x -> (partitions ! x) `mod` 1000000 == 0) [1..]

Problem 79

By analysing a user's login attempts, can you determine the secret numeric passcode?

Solution:

A bit ugly but works fine

import Data.List
 
problem_79 :: String -> String
problem_79 file = 
    map fst $ 
    sortBy (\(_,a) (_,b) ->
        compare (length b) (length a)) $
    zip digs order
    where
    nums = lines file
    digs = 
        map head $ group $
        sort $ filter (\c -> c >= '0' && c <= '9') file
    prec = concatMap (\(x:y:z:_) -> [[x,y],[y,z],[x,z]]) nums
    order = 
        map (\n -> map head $
            group $ sort $ map (\(_:x:_) -> x) $ 
        filter (\(x:_) -> x == n) prec) digs
main=do 
    f<-readFile "keylog.txt"
    print$problem_79 f

Problem 80

Calculating the digital sum of the decimal digits of irrational square roots.

Solution:

import Data.List ((\\))

hundreds :: Integer -> [Integer]
hundreds n = hundreds' [] n
    where
        hundreds' acc 0 = acc
        hundreds' acc n = hundreds' (m : acc) d
            where
                (d,m) = divMod n 100

squareDigs :: Integer -> [Integer]
squareDigs n = p : squareDigs' p r xs
    where
        (x:xs) = hundreds n ++ repeat 0
        p = floor $ sqrt $ fromInteger x
        r = x - (p^2)

squareDigs' :: Integer -> Integer -> [Integer] -> [Integer]
squareDigs' p r (x:xs) =
    x' : squareDigs' (p*10 + x') r' xs
    where
    n = 100*r + x
    (x',r') = 
        last $ takeWhile
        (\(_,a) -> a >= 0) $
        scanl (\(_,b) (a',b') -> (a',b-b')) (0,n) rs
    rs = [y|y <- zip [1..] [(20*p+1),(20*p+3)..]]
        
sumDigits n = sum $ take 100 $ squareDigs n

problem_80 :: Integer
problem_80 = 
    sum $ map sumDigits 
    [x|x <- [1..100] \\ [n^2|n<-[1..10]]]