Haskell: Faster Summation of Primes

Disclaimer: I am working on Euler 9 issue.

I add some pretty large numbers, all primes from 1 to 2,000,000.

The summation of these primes takes place forever. I use haskell built into the sum function.

how in:

sum listOfPrimes

Are there any other faster options?

- My primary generator was a slow reference in my code.

+3
source share
4 answers

It seems your problem is not summing up the numbers, but generating them. What is your implementation of listOfPrimes?

This article may be of interest: http://lambda-the-ultimate.org/node/3127

+12
source

, ghc -O2, ghci, ? , .

- , . :

import Data.List
import qualified Data.Map as M

primes :: [Integer]
primes = mkPrimes 2 M.empty
  where
    mkPrimes n m = case (M.null m, M.findMin m) of
        (False, (n', skips)) | n == n' ->
            mkPrimes (succ n) (addSkips n (M.deleteMin m) skips)
        _ -> n : mkPrimes (succ n) (addSkip n m n)
    addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m
    addSkips = foldl' . addSkip

-- fuse:
main = print (sum (takeWhile (<= 2000000) primes))

,

$ ghc -O2 --make A.hs
$ time ./A           
142913828922
./A  9.99s user 0.17s system 99% cpu 10.166 total

, . takeWhile :

import qualified Data.List.Stream as S
main = print (S.sum (S.takeWhile (<= 2000000) primes))

,

$ time ./A           
142913828922
./A  9.60s user 0.13s system 99% cpu 9.795 total

, , , :

$ time ./A           
1999993
./A  9.65s user 0.12s system 99% cpu 9.768 total

, .: -)

, Hackage :

http://hackage.haskell.org/packages/archive/primes/0.1.1/doc/html/Data-Numbers-Primes.html

, :

$ cabal install primes
$ cabal install stream-fusion

$ cat A.hs
import qualified Data.List.Stream as S
import Data.Numbers.Primes

main = print . S.sum . S.takeWhile (<= 2000000) $ primes

$ ghc -O2 -fvia-C -optc-O3 A.hs --make

$ time ./A
142913828922
./A  0.62s user 0.07s system 99% cpu 0.694 total
+9

- , , , sum. :

isprime :: (Integral i) => i -> Bool
isprime n = isprime_ n primes
  where isprime_ n (p:ps)
          | p*p > n        = True
          | n `mod` p == 0 = False
          | otherwise      = isprime_ n ps

primes :: (Integral i) => [i]
primes = 2 : filter isprime [3,5..]

, , , , , , primes. , .

+7

" " :

import Data.List
import qualified Data.Map as M
primes :: [Integer]
primes = mkPrimes 2 M.empty
  where
    mkPrimes n m = case (M.null m, M.findMin m) of
        (False, (n', skips)) | n == n' ->
            mkPrimes (succ n) (addSkips n (M.deleteMin m) skips)
        _ -> n : mkPrimes (succ n) (addSkip n m n)
    addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m
    addSkips = foldl' . addSkip

, 25 print . sum $ takeWhile (<= 20000000) . ? , J 1

   +/p:i.p:^:_1]20000000
12272577818052

.

+5

Source: https://habr.com/ru/post/1712809/


All Articles