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
Related videos on Youtube
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, 2022Comments
-
ceth almost 2 years
I need a function which gets two
Int
s (a
andb
) and returnsA/B
asInt
. I am sure thatA/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 over 13 yearsOr
a `quot` b
for the infix lovers (wow, you can actually escape backticks insice backticks with backslash?). -
Antal Spector-Zabusky over 13 yearsAlso
a `div` b
; if I remember correctly,quot
truncates (like demas wanted), anddiv
rounds towards zero. So(-3) `quot` 4 == 0
, and(-3) `div` 4 == -1
. -
luqui over 13 years+1 for
div
. More mathematically well-behaved,quot
is a bitch when there are negative numbers around. -
MuffinTheMan over 10 yearsThis was a life-saver for me. I was wrestling with
fromIntegral (ceiling (int1 / int2))
and other things--none of which gave me back anInt
, but this one did. -
Lacuno about 9 years
div
rounds towards negative inifinity, not zero. -
Ruud Helderman about 5 yearsNice 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 over 2 yearsin 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 over 2 years@mLstudent33 I hope it's clear that you're responding to an 11 year old answer