Skip to content

Instantly share code, notes, and snippets.

@tmountain
Created October 10, 2017 20:10
Show Gist options
  • Save tmountain/6e063d36784b9ce7521f45f0eda06355 to your computer and use it in GitHub Desktop.
Save tmountain/6e063d36784b9ce7521f45f0eda06355 to your computer and use it in GitHub Desktop.
-- problem 1
sum [ x | x <- [1..999], x `mod` 3 == 0 || x `mod` 5 == 0 ]
-- problem 2
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
sum [ x | x <- takeWhile (<= 4*10^6) $ drop 2 fibs, even ]
-- problem 3
prime n
| n < 2 = False
| n == 2 = True
| even n = False
| n == 3 = True
| otherwise = all (/=0) $ map (\x -> n `mod` x) [3,5..n `div` 2]
isFactor n x = n `mod` x == 0
-- only consider the range up to the √ of the number under consideration
take 1 $ filter (\x -> (isFactor 600851475143 x) && prime x) [775146,775145..1]
-- problem 4
import Data.List
import Data.Ord
isPalindrome [x, y] =
let n = x * y
in if show n == reverse (show n)
then True
else False
pairs = [[x, y] | x <- [100..999], y <- [100..999]]
head $ reverse $ sortBy (comparing product) $ filter isPalindrome pairs
-- problem 5
-- https://www.algebra.com/algebra/homework/divisibility/Divisibility_and_Prime_Numbers.faq.question.505530.html
import Data.Numbers.Primes
occ x = length . filter (== x)
maxPF x xs = maximum $ map (occ x . primeFactors) xs
maxPF' = flip maxPF $ [2..20]
foldr1 (*) $ filter (> 1) $ zipWith (^) [2..20] $ map maxPF' [2..20]
-- problem 6
(sum [1..100])^2 - sum (map (^2) [1..100])
-- problem 7
primes = 2 : primes'
where isPrime (p:ps) n = p*p > n || n `rem` p /= 0 && isPrime ps n
primes' = 3 : filter (isPrime primes') [5, 7 ..]
primes !! 10000
-- problem 8
digs 0 = []
digs x = digs (x `div` 10) ++ [x `mod` 10]
maximum $ map (foldr1 (*)) $ map (\n -> take 13 $ drop n $ digs bigNum) [0..(length $ digs bigNum) - 13]
-- problem 9
st (a, b, c) = a + b + c
filter (\x -> st x == 1000) [ (a,b,c) | c <- [1..1000], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2]
-- problem 10 (use primes definition from problem 7)
sum $ takeWhile (<2000000) primes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment