0

So here is my code to find the factors of a number n, excluding n and 1.

factors :: Int -> [Int]
factors n = [x | x <- [2..(intSquareRoot n)], n `mod` x ==0]

intSquareRoot :: Int -> Int
intSquareRoot n = intSq n
  where
    intSq x
      | x*x > n = intSq (x - 1)
      | otherwise = x

it finds the factors of n upto sqrt(n), then I want to add the rest of factors. The code I want would look like this

factors :: Int -> [Int]
factors n = [x | x <- [2..(intSquareRoot n)], n `mod` x ==0]
          ++[1/x | x <- [2..(intSquareRoot n)], n `mod` x ==0]

But Haskell gives me the error that it expects a fractional number, which is understandable because I am dividing it. However, I know that for all x satisfying the conditions of the list, n/x will be an integer. How do I get around this error? Thanks in advance!

bheklilr
  • 53,530
  • 6
  • 107
  • 163
Slugger
  • 665
  • 1
  • 5
  • 17
  • Even if `x` is an `Int`, ```1 `quot` x``` will always be 0 or `-1`. Did you mean `n / x`? And to get around it, you can use the `quot` function instead, and there's the `quotRem` function which calculates the modulus at the same time. – bheklilr Sep 15 '14 at 18:56
  • since your question was really about how to do integer division in Haskell, I marked it as a duplicate of this popular-looking answer that explains `div`, `mod`, `quot`, and `rem` with more information than provided in my comment above. – bheklilr Sep 15 '14 at 19:24
  • @did you mean `n/x` in the 2nd list comprehension? (i.e. `div n x`). You don't need to search for them again, they are already at your disposal in the 1st comprehension: `factors n = let xqs = [(x,q) | x<-[2..isqrt n], x*x – Will Ness Sep 15 '14 at 20:49

0 Answers0