Euler problems/1 to 10

From HaskellWiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Problem 1

Add all the natural numbers below 1000 that are multiples of 3 or 5.

Solution:

problem_1 = sum [ x | x <- [1..1000], (x `mod` 3 == 0) ||  (x `mod` 5 == 0)]

Problem 2

Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed one million.

Solution:

problem_2 = sum [ x | x <- fibs, x `mod` 2 == 0]
  where fibs = 1 : 1 : zipWith (+) fibs (tail fibs)

Problem 3

Find the largest prime factor of 317584931803.

Solution:

problem_3 = maximum [ x | x <- [1..round $ sqrt (fromInteger c)], c `mod` x == 0]
  where c = 317584931803

Problem 4

Find the largest palindrome made from the product of two 3-digit numbers.

Solution:

problem_4 = foldr max 0 [ x | y <- [100..999], z <- [100..999], let x = y * z, let s = show x, s == reverse s]

Problem 5

What is the smallest number divisible by each of the numbers 1 to 20?

Solution:

problem_5 = head [ x | x <- [2520,5040..], all (\y -> x `mod` y == 0) [1..20]]

Problem 6

What is the difference between the sum of the squares and the square of the sums?

Solution:

problem_6 = sum [ x^2 | x <- [1..100]] - (sum [1..100])^2

Problem 7

Find the 10001st prime.

Solution:

problem_7 = head $ drop 10000 primes
  where primes = 2:3:..

Problem 8

Discover the largest product of five consecutive digits in the 1000-digit number.

Solution:

problem_8 = undefined

Problem 9

Find the only Pythagorean triplet, {a, b, c}, for which a + b + c = 1000.

Solution:

problem_9 = head [a*b*c | a <- [1..500], b <- [a..500], c <- [1..(1000-a-b)], a + b + c == 1000,  a^2 + b^2 == c^2]


Problem 10

Calculate the sum of all the primes below one million.

Solution:

problem_10 = sum [ p | p <- primes, p < 1000000 ]