Sexy primes: Difference between revisions
Content deleted Content added
m →{{header|Haskell}}: second example with a single fold |
|||
Line 700:
quads = foldr (\a b -> if isPrime (a-18) && isPrime (a-12) && isPrime (a-6) then (a-18,a-12,a-6,a) : b else b) [] d
quins = foldr (\a b -> if isPrime (a-24) && isPrime (a-18) && isPrime (a-12) && isPrime (a-6) then (a-24, a-18,a-12,a-6,a) : b else b) [] d
lastFive xs = show $ drop (length xs - 5) xs
lastFiveText = " Last 5 : %s\n\n"
</lang>
Or using a single fold for increased efficiency
<lang haskell>
import Text.Printf (printf)
import Data.Numbers.Primes (isPrime, primes)
data Result = Result [(Int, Int)] [(Int, Int, Int)] [(Int, Int, Int, Int)] [(Int, Int, Int, Int, Int)]
groups :: Int -> Result -> Result
groups a r@(Result p t q qn)
| isPrime (a-24) && isPrime (a-18) && isPrime (a-12) && isPrime (a-6) = Result asPair asTriplet asQuad asQuin
| isPrime (a-18) && isPrime (a-12) && isPrime (a-6) = Result asPair asTriplet asQuad qn
| isPrime (a-12) && isPrime (a-6) = Result asPair asTriplet q qn
| isPrime (a-6) = Result asPair t q qn
| otherwise = r
where asPair = (a-6, a) : p
asTriplet = (a-12, a-6,a) : t
asQuad = (a-18, a-12, a-6, a) : q
asQuin = (a-24, a-18, a-12, a-6, a) : qn
main :: IO ()
main = do
printf ("Number of sexy prime pairs: %d\n" ++ lastFiveText) (length pairs) (lastFive pairs)
printf ("Number of sexy prime triplets: %d\n" ++ lastFiveText) (length triplets) (lastFive triplets)
printf ("Number of sexy prime quadruplets: %d\n" ++ lastFiveText) (length quads) (lastFive quads)
printf "Number of sexy prime quintuplets: %d\n Last 1 : %s\n\n" (length quins) (show $ drop (length quins -1) quins)
printf "Number of unsexy primes: %d\n Last 10: %s\n\n" (length unsexy) (show $ drop (length unsexy - 10) unsexy)
where d = takeWhile (< 1000035) primes
unsexy = filter (\n -> (not $ isPrime (n+6)) && (not $ isPrime (n-6))) d
(Result pairs triplets quads quins) = foldr groups (Result [] [] [] []) d
lastFive xs = show $ drop (length xs - 5) xs
lastFiveText = " Last 5 : %s\n\n"
|