Add Haskell solutions for Problems 4, 5, 6, 7
This commit is contained in:
parent
327998ae0f
commit
b6b10cdd12
15
Haskell/p004.hs
Normal file
15
Haskell/p004.hs
Normal file
@ -0,0 +1,15 @@
|
||||
-- A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
|
||||
--
|
||||
-- Find the largest palindrome made from the product of two 3-digit numbers.
|
||||
|
||||
isPalindrome :: Integer -> Bool
|
||||
isPalindrome n = show n == (reverse $ show n)
|
||||
|
||||
maxPalindrome :: Integer
|
||||
maxPalindrome =
|
||||
maximum $ filter isPalindrome [ x * y | x <- [100..999], y <- [100..999] ]
|
||||
|
||||
main = do
|
||||
let result = maxPalindrome
|
||||
putStrLn $ "Project Euler, Problem 4\n"
|
||||
++ "Answer: " ++ (show result)
|
13
Haskell/p005.hs
Normal file
13
Haskell/p005.hs
Normal file
@ -0,0 +1,13 @@
|
||||
-- 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
|
||||
--
|
||||
-- What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
|
||||
|
||||
lcmm :: (Integral n) => [n] -> n
|
||||
lcmm values
|
||||
| length values == 2 = lcm (head values) (last values)
|
||||
| otherwise = lcm (head values) (lcmm (tail values))
|
||||
|
||||
main = do
|
||||
let result = lcmm [1..20]
|
||||
putStrLn $ "Project Euler, Problem 5\n"
|
||||
++ "Answer: " ++ (show result)
|
19
Haskell/p006.hs
Normal file
19
Haskell/p006.hs
Normal file
@ -0,0 +1,19 @@
|
||||
-- The sum of the squares of the first ten natural numbers is,
|
||||
--
|
||||
-- 1^2 + 2^2 + ... + 10^2 = 385
|
||||
--
|
||||
-- The square of the sum of the first ten natural numbers is,
|
||||
--
|
||||
-- (1 + 2 + ... + 10)^2 = 55^2 = 3025
|
||||
--
|
||||
-- Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
|
||||
--
|
||||
--Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
|
||||
|
||||
sumSquareDiff :: Integer -> Integer
|
||||
sumSquareDiff n = (sum [1..n]^2) - (sum $ map (^2) [1..n])
|
||||
|
||||
main = do
|
||||
let result = sumSquareDiff 100
|
||||
putStrLn $ "Project Euler, Problem 6\n"
|
||||
++ "Answer: " ++ (show result)
|
13
Haskell/p007.hs
Normal file
13
Haskell/p007.hs
Normal file
@ -0,0 +1,13 @@
|
||||
-- By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
|
||||
--
|
||||
-- What is the 10 001st prime number?
|
||||
--
|
||||
import ProjectEuler (isPrime)
|
||||
|
||||
nthPrime :: (Integral a) => Int -> a
|
||||
nthPrime n = last $ take n [ x | x <- [1..], isPrime x ]
|
||||
|
||||
main = do
|
||||
let result = nthPrime 10001
|
||||
putStrLn $ "Project Euler, Problem 7\n"
|
||||
++ "Answer: " ++ (show result)
|
Loading…
x
Reference in New Issue
Block a user