Reputation: 1480
I want to find all numbers up to N in Haskell, that satisfies the equation (Fermat theorem):
Some solutions could be:
So I try to do it like so in Haskell:
main :: IO ()
main = do
let arr = [ z * z == x * x + y * y | x <- [1..13], y <- [1..13], z <- [1..13]] in print arr
I get bool values list:
[False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,...]
There are 4 True values in total in that list. My questons are:
UPDATE: One more question. How can I count how many numbers do not belong to ANY tuple? I thought it would logically go like this:
solutions2 = [
(z)
| x <- [1..13]
, y <- [x..13]
, z <- [y..13]
, z * z /= x * x + y * y,
z * z /= x * x - y * y,
z * z /= y * y - x * x
]
But that returned way too many numbers. Any ideas about how to find numbers that do not belong to any triples?
UPDATE2: I have been experimenting and diging more. How can I pass number n, that I read from input to a previously efined function (calculation method)? I would like to be able to get solution array, print it and its lenght.
sol n = solution = [
(x, y, z)
| x <- [1..n]
, y <- [x..n]
, z <- [y..n]
, z * z == x * x + y * y
]
main :: IO ()
main = do
putStrLn "Enter n:"
n <- getLine
let mySol = sol n
print (mySol)
But i gives me error:
error: parse error on input `='
and also:
Failed, no modules loaded.
Upvotes: 1
Views: 378
Reputation: 476813
You can work with a filter and yield an (x, y, z)
tuple in case the filter is satisfied:
solutions = [
(x, y, z)
| x <- [1..13]
, y <- [1..13]
, z <- [1..13]
, z * z == x * x + y * y
]
main :: IO ()
main = do
print solutions
This gives us the six solutions:
Prelude> solutions
[(3,4,5),(4,3,5),(5,12,13),(6,8,10),(8,6,10),(12,5,13)]
You can also print print (length solutions)
to obtain the number of solutions.
Upvotes: 4