Advertisement
banovski

Project Euler, Problem #7, Haskell

Dec 20th, 2021 (edited)
1,563
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we
  2. -- can see that the 6th prime is 13. What is the 10 001st prime
  3. -- number?
  4.  
  5.  
  6. -- Solution #1: a basic one
  7.  
  8. main :: IO ()
  9. main =
  10.   print $
  11.   [x | x <- [1 ..], null [y | y <- [2 .. div x 2], mod x y == 0]] !! 10001
  12.  
  13.  
  14. -- 104743
  15.  
  16.  
  17. -- real 0m40,243s
  18. -- user 0m39,956s
  19. -- sys  0m0,248s
  20.  
  21. -- #################################
  22. -- Solution #2: still basic, but faster
  23.  
  24.  
  25. -- The idea behind this solution is that, if a number can't be divided
  26. -- by any prime number smaller than itself, then this number is prime
  27. -- itself. The checked number "cn" is checked against the list of prime
  28. -- numbers "pl". If the number is prime, it's added to the list; if
  29. -- it's not, then it's incremented and checked again. The list is
  30. -- expanded as long as its size is less than 10001; when the length of
  31. -- the list is equal to 10001 its last item is returned.
  32.  
  33.  
  34. -- pcc (prime checker concatenator) definition #1: if an auxiliary
  35. -- copy of the list of primes is empty, which means that the checked
  36. -- number is prime, then the number is added to the main list of
  37. -- primes and then the number is incremented.
  38.  
  39. pcc :: Integral t => [t] -> [t] -> t -> t
  40. pcc pl [] cn = lsc (pl ++ [cn]) (cn + 1)
  41.  
  42.  
  43. -- pcc definition #2: the checked number is recursively checked
  44. -- against numbers in an auxiliary copy of the list of prime numbers;
  45. -- the numbers on the list go in ascending order, so smaller, thus
  46. -- more likely divisors are checked first.
  47.  
  48. pcc pl (x:xs) cn =
  49.   if mod cn x == 0
  50.     then pcc pl pl (cn + 1)
  51.     else pcc pl xs cn
  52.  
  53.  
  54. -- lsc (list size checker) definition: the length of the main list is
  55. -- checked: if it's equal to 10001, then the last item of the main
  56. -- list of prime numbers is returned, otherwise incrementation, check
  57. -- and list expansion continue.
  58.  
  59. lsc :: Integral t => [t] -> t -> t
  60. lsc pl cn =
  61.   if length pl < 10001
  62.     then pcc pl pl cn
  63.     else last pl
  64.  
  65. main :: IO ()
  66. main = print $ lsc [2] 3
  67.  
  68. -- 104743
  69.  
  70. -- real 0m15,728s
  71. -- user 0m15,596s
  72. -- sys  0m0,077s
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement