haskell - Convert Int into [Int] -
i'm looking through past exam paper , don't understand how convert int [int]. example, 1 of questions asks produce list of factors of whole number excluding both number , 1.
strictfactors int -> [int] strictfactors x = ??? i'm not asking question me! want know how i'd convert integer input list of integer output. thanks!
perhaps easiest have @ similar code. requested, won't give answer, should able use these ideas want.
brute force
here we're going use pairs of numbers between 1 , x test if can make x sum of 2 square numbers:
sumofsquares :: int -> [int] sumofsquares x = [ (a,b) | <- [1..x], b <- [a..x], a^2 + b^2 == x] you call this:
ghci> assumofsquares 50 [(1,7),(5,5)] because 50 = 1^2+7^2 , 50 = 5^2 + 5^2.
you can think of sumofsquares working first taking a list [1..x] of numbers between 1 , x , between , x. checks a^2 + b^2 == x. if that's true, adds (a,b) resulting list.
generate , check
this time let's generate single numbers check whether they're multiple of another. calculate least common multiple (lcm). example, least common multiple of 15 , 12 60, because it's first number that's in both 15 , 12 times tables.
this function isn't of type want uses techniques want.
lcm :: int -> int -> int lcm x y = head [x*a | <- [1..], (x*a) `mod` y == 0] you can call this:
ghci> lcm 12 15 60 this time list of numbers [1..] (in principle) infinite; job we're picking first 1 head!
(x*a) `mod` y == 0 checking see whether number x*a multiple of y (mod gives remainder after division). that's key idea should use.
summary
use a <- [1..end] generate numbers, test them true/false expression (i.e. bool), perhaps using mod function.
Comments
Post a Comment