Last active
December 30, 2015 10:39
-
-
Save clrnd/7817392 to your computer and use it in GitHub Desktop.
Data.Sequence lol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Text.Printf | |
import System.CPUTime | |
import qualified Data.Sequence as Seq | |
import Data.Sequence ((><), (<|), (|>)) | |
import Data.Foldable (toList) | |
time :: IO t -> IO t | |
time a = do | |
start <- getCPUTime | |
v <- a | |
end <- getCPUTime | |
let diff = (fromIntegral (end - start)) / (10^12) | |
printf "Computation time: %0.3f sec\n" (diff :: Double) | |
return v | |
-- 1 | |
filtrarPrimos [] = [] | |
filtrarPrimos (x:xs) = x : filtrarPrimos [ a | a <- xs, mod a x /= 0 ] | |
filtrarPrimosHasta :: Int -> [Int] | |
filtrarPrimosHasta n = filtrarPrimos [2..n] | |
-- 2 | |
criba [] = [] | |
criba (x:xs) = x : criba (filter noMultiploDeX xs) | |
where noMultiploDeX m = mod m x /= 0 | |
primosHasta :: Int -> [Int] | |
primosHasta n = 2 : criba [3,5..n] | |
-- 3 | |
primesBelow' n result numbers | |
| p^2 <= n = primesBelow' n (result ++ [p]) (filter (\x -> mod x p /= 0) (tail numbers)) | |
| otherwise = result ++ numbers | |
where p = head numbers | |
primesBelow :: Int -> [Int] | |
primesBelow n = 2 : primesBelow' n [] [3,5..n] | |
-- 4 | |
megaPrimos' :: Int -> Seq.Seq Int -> Seq.Seq Int -> Seq.Seq Int | |
megaPrimos' n result numbers | |
| p^2 <= n = megaPrimos' n (result |> p) (Seq.filter (\x -> mod x p /= 0) (Seq.drop 1 numbers)) | |
| otherwise = result >< numbers | |
where p = Seq.index numbers 0 | |
megaPrimos :: Int -> Seq.Seq Int | |
megaPrimos n = 2 <| megaPrimos' n Seq.empty (Seq.fromList [3,5..n]) | |
-- test | |
testF f limit range = sum $ map (\x -> sum $ f x) [(limit-range)..limit] | |
lol = 170000 | |
r = 500 | |
main = do | |
--time $ putStrLn $ show $ testF primosHasta lol r | |
--time $ putStrLn $ show $ testF filtrarPrimosHasta lol r | |
--time $ putStrLn $ show $ testF primesBelow lol r | |
--time $ putStrLn $ show $ testF megaPrimos lol r | |
time $ putStrLn $ show $ (reverse $ primesBelow lol) !! 0 | |
time $ putStrLn $ show $ Seq.index (Seq.reverse $ megaPrimos lol) 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment