Divide Int to Int and return Int

54,274

Solution 1

Why not just use quot?

quot a b

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

Solution 2

Here's what I did to make my own:

quot' a b
         | a<b = 0  -- base case
         | otherwise = 1 + quot' a-b b
Share:
54,274

Related videos on Youtube

ceth
Author by

ceth

I'm a programmer, occasional SRE, Unix automator. I'm currently working primarily in Go, and prior to that my weapon of choice was Python, but I'm also familiar with Java, C#, JavaScript, and bash. I dabble in Clojure and F# but I've never thrown a big problem at it. I run Linux at home and at work but that doesn't mean I'm ignorant of other systems :)

Updated on July 05, 2022

Comments

  • ceth
    ceth almost 2 years

    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 ?

  • Admin
    Admin over 13 years
    Or a `quot` b for the infix lovers (wow, you can actually escape backticks insice backticks with backslash?).
  • Antal Spector-Zabusky
    Antal Spector-Zabusky over 13 years
    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.
  • luqui
    luqui over 13 years
    +1 for div. More mathematically well-behaved, quot is a bitch when there are negative numbers around.
  • MuffinTheMan
    MuffinTheMan over 10 years
    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.
  • Lacuno
    Lacuno about 9 years
    div rounds towards negative inifinity, not zero.
  • Ruud Helderman
    Ruud Helderman about 5 years
    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).
  • mLstudent33
    mLstudent33 over 2 years
    in ghci: <interactive>:12:1: error: • Non type-variable argument in the constraint: Fractional (a -> a) (Use FlexibleContexts to permit this) • When checking the inferred type it :: forall a. (Fractional (a -> a), Integral a) => a -> a
  • Pointy
    Pointy over 2 years
    @mLstudent33 I hope it's clear that you're responding to an 11 year old answer