Sexy primes: Difference between revisions

m
Line 741:
</pre>
Slight variation which only holds on to the display results. Does not perform any better than above though. Both run ~ 250ms.
<lang haskell>import{-# Control.LensLANGUAGE TemplateHaskell (_1, _2, _3, _4, _5, over)#-}
import Control.Lens (makeLenses, over, (^.), to, view)
import Data.Numbers.Primes (isPrime, primes)
import Text.Printf (printf)
 
data Group a = Group { _count :: Int, _results :: [a] } deriving (Show)
type Pair = (Int, [(Int, Int)])
makeLenses ''Group
type Triplet = (Int, [(Int, Int, Int)])
type Quad = (Int, [(Int, Int, Int, Int)])
type Quin = (Int, [(Int, Int, Int, Int, Int)])
type UnSexy = (Int, [Int])
 
type Result = (Pair, Triplet, Quad,Group Quin(Int, UnSexyInt)
type DisplayResult = ((Int, String), (Int, String), (Int, String) , Group (Int, String)Int, (Int, String))
type Triplet = , Group (Int, [(Int, Int, Int)])
type Quad = , Group (Int, [(Int, Int, Int, Int)])
, Group Int)
 
emptyGroupsinitialGroups :: Result
initialGroups = let newGroup = Group 0 []
emptyGroups = ((0, []), (0, []), (0, []), (0, []), (0, []))
in (newGroup, newGroup, newGroup, newGroup, newGroup)
 
groupscompute :: Result -> Int -> Result
groupscompute r@(pr, tt, qd, qn, un) n
| isPrime n4 && isPrime n3 && isPrime n2 && isPrime n1 = (addPair pr, addTriplet tt, addQuad qd, addQuin qn, un)
| isPrime n3 && isPrime n2 && isPrime n1 = (addPair pr, addTriplet tt, addQuad qd, qn, un)
Line 771 ⟶ 773:
n4 = n-24
 
addPair = over _1count succ . over _2results (take 5 . (:) (n1, n))
addTriplet = over _1count succ . over _2results (take 5 . (:) (n2, n1, n))
addQuad = over _1count succ . over _2results (take 5 . (:) (n3, n2, n1, n))
addQuin = over _1count succ . over _2results (take 1 . (:) (n4, n3, n2, n1, n))
addUnSexy = over _1count succ . over _2results (take 10 . (:) n)
 
display :: Result -> DisplayResult
display = over _1 f . over _2 f . over _3 f . over _4 f . over _5 f
where
f :: Show b => (a, [b]) -> (a, String)
f = over _2 show . over _2 reverse
 
main :: IO ()
main = do
let (pairspr, tripletstt, quadsqd, quinsqn, unsexyun) = collectGroups primes
uncurry (printf "Number of sexy prime pairs: %d\n Last 5 : %s\n\n" (pr ^. count) pairs(pr ^. results . to (show . reverse))
uncurry (printf "Number of sexy prime triplets: %d\n Last 5 : %s\n\n" (tt ^. count) triplets(tt ^. results . to (show . reverse))
uncurry (printf "Number of sexy prime quadruplets: %d\n Last 5 : %s\n\n" (qd ^. count) quads(qd ^. results . to (show . reverse))
uncurry (printf "Number of sexy prime quintuplets: %d\n Last 1 : %s\n\n" (qn ^. count) quins(qn ^. results . to (show . reverse))
uncurry (printf "Number of unsexy primes: %d\n Last 10: %s\n\n" (un ^. count) unsexy(un ^. results . to (show . reverse))
where
collectGroups = display . foldl groupscompute emptyGroupsinitialGroups . takeWhile (< 1000035)</lang>
</lang>
 
=={{header|Java}}==
Anonymous user