80

I need a function which gets two Ints (a and b) and returns A/B as Int. I am sure that A/B will always be an integer.

Here is my solution:

myDiv :: Int -> Int -> Int
myDiv a b = 
      let x = fromIntegral a
          y = fromIntegral b
      in truncate (x / y)

But want to find more simpler solution. Something like this:

myDiv :: Int -> Int -> Int
myDiv a b = a / b

How can I divide Int to Int and get Int ?

2 Answers 2

145

Why not just use quot?

quot a b

is the integer quotient of integers a and b truncated towards zero.

Sign up to request clarification or add additional context in comments.

7 Comments

Or a `quot` b for the infix lovers (wow, you can actually escape backticks insice backticks with backslash?).
Also a `div` b; if I remember correctly, quot truncates (like demas wanted), and div rounds towards zero. So (-3) `quot` 4 == 0, and (-3) `div` 4 == -1.
+1 for div. More mathematically well-behaved, quot is a bitch when there are negative numbers around.
This was a life-saver for me. I was wrestling with fromIntegral (ceiling (int1 / int2)) and other things--none of which gave me back an Int, but this one did.
div rounds towards negative inifinity, not zero.
|
1

Here's what I did to make my own:

quot' a b
         | a<b = 0  -- base case
         | otherwise = 1 + quot' a-b b

1 Comment

Nice as an exercise, but useless in production. On large numbers it is slow (linear time) and has a high memory footprint (not tail-recursive). For negative numbers, it is either wrong (a<0) or never ends (b<0).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.