Pythagorean triples: Difference between revisions

Content added Content deleted
m (→‎using single evenness for determinacy: elided a word from the output section.)
m (→‎{{header|Haskell}}: Applied Ormolu, preferred <> to ++)
Line 2,227: Line 2,227:
(\(_, a, b, c) -> a + b + c <= n)
(\(_, a, b, c) -> a + b + c <= n)
[ (prim a b c, a, b, c)
[ (prim a b c, a, b, c)
| a <- xs
| a <- xs,
, b <- drop a xs
b <- drop a xs,
, c <- drop b xs
c <- drop b xs,
, a ^ 2 + b ^ 2 == c ^ 2 ]
a ^ 2 + b ^ 2 == c ^ 2
]
where
where
xs = [1 .. n]
xs = [1 .. n]
Line 2,238: Line 2,239:
main =
main =
putStrLn $
putStrLn $
"Up to 100 there are " ++
"Up to 100 there are "
show (length xs) ++
<> show (length xs)
" triples, of which " ++
<> " triples, of which "
show (length $ filter (\(x, _, _, _) -> x) xs) ++ " are primitive."
<> show (length $ filter (\(x, _, _, _) -> x) xs)
<> " are primitive."
where
where
xs = pytr 100</lang>
xs = pytr 100</lang>
Line 2,249: Line 2,251:


Or equivalently (desugaring the list comprehension down to nested concatMaps, and pruning back the search space a little):
Or equivalently (desugaring the list comprehension down to nested concatMaps, and pruning back the search space a little):
<lang haskell>pythagoreanTriplesBelow :: Int -> [[Int]]
<lang haskell>------------------- PYTHAGOREAN TRIPLES ------------------

pythagoreanTriplesBelow :: Int -> [[Int]]
pythagoreanTriplesBelow n =
pythagoreanTriplesBelow n =
concatMap
let m = quot n 2
in concatMap
( \x ->
(\x ->
concatMap
concatMap
(\y -> concatMap (go x y) [y + 1 .. m])
(\y ->
[x + 1 .. m]
)
concatMap
(\z ->
[1 .. m]
where
if x + y + z <= n && x ^ 2 + y ^ 2 == z ^ 2
m = quot n 2
then [[x, y, z]]
go x y z
else [])
[y + 1 .. m])
| x + y + z <= n && x ^ 2 + y ^ 2 == z ^ 2 =
[x + 1 .. m])
[[x, y, z]]
[1 .. m]
| otherwise = []


-- TEST -------------------------------------------------------------------------
--------------------------- TEST -------------------------
main :: IO ()
main :: IO ()
main =
main =
mapM_
mapM_
(print . length)
(print . length)
([id, filter (\[x, y, _] -> gcd x y == 1)] <*> [pythagoreanTriplesBelow 100])</lang>
( [id, filter (\[x, y, _] -> gcd x y == 1)]
<*> [pythagoreanTriplesBelow 100]
)</lang>
{{Out}}
{{Out}}
<pre>17
<pre>17
Line 2,286: Line 2,292:
map
map
(map (sum . zipWith (*) t))
(map (sum . zipWith (*) t))
[ [[1, -2, 2], [2, -1, 2], [2, -2, 3]]
[ [[1, -2, 2], [2, -1, 2], [2, -2, 3]],
, [[1, 2, 2], [2, 1, 2], [2, 2, 3]]
[[1, 2, 2], [2, 1, 2], [2, 2, 3]],
, [[-1, 2, 2], [-2, 1, 2], [-2, 2, 3]]
[[-1, 2, 2], [-2, 1, 2], [-2, 2, 3]]
]
]


Line 2,298: Line 2,304:
main =
main =
mapM_
mapM_
((putStrLn . (\n -> show n ++ " " ++ show (triangleCount n))) . (10 ^))
((putStrLn . (\n -> show n <> " " <> show (triangleCount n))) . (10 ^))
[1 .. 7]</lang>
[1 .. 7]</lang>
{{out}}
{{out}}