Coprime triplets: Difference between revisions

→‎{{header|Haskell}}: Added a solution using Haskell
(Added Algol 68)
(→‎{{header|Haskell}}: Added a solution using Haskell)
Line 151:
1 2 3 5 4 7 9 8 11 13 6 17 19 10 21 23 16 15 29 14 25 27 22 31 35 12 37 41 18 43 47 20 33 49 26 45
</pre>
 
=={{header|Haskell}}==
<lang haskell>import Data.List (find, transpose, unfoldr)
import Data.List.Split (chunksOf)
import qualified Data.Set as S
 
--------------------- COPRIME TRIPLES --------------------
 
coprimeTriples :: Integral a => [a]
coprimeTriples =
[1, 2] <> unfoldr go (S.fromList [1, 2], (1, 2))
where
go (seen, (a, b)) =
Just
(nxt, (S.insert nxt seen, (b, nxt)))
where
(Just nxt) =
find
( (<*>)
((&&) . flip S.notMember seen)
( (<*>)
((&&) . flip coprime a)
(`coprime` b)
)
)
[3 ..]
 
coprime :: Integral a => a -> a -> Bool
coprime a b = 1 == gcd a b
 
--------------------------- TEST -------------------------
main :: IO ()
main =
let xs = takeWhile (< 50) coprimeTriples
in putStrLn (show (length xs) <> " terms below 50:\n")
>> putStrLn
( spacedTable
justifyRight
(chunksOf 10 (fmap show xs))
)
 
-------------------------- FORMAT ------------------------
 
spacedTable ::
(Int -> Char -> String -> String) -> [[String]] -> String
spacedTable aligned rows =
let columnWidths =
fmap
(maximum . fmap length)
(transpose rows)
in unlines $
fmap
(unwords . zipWith (`aligned` ' ') columnWidths)
rows
 
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</lang>
{{Out}}
<pre>36 terms below 50:
 
1 2 3 5 4 7 9 8 11 13
6 17 19 10 21 23 16 15 29 14
25 27 22 31 35 12 37 41 18 43
47 20 33 49 26 45</pre>
 
 
=={{header|Julia}}==
9,659

edits