[erlang-questions] Flooring integer division in Erlang?

Igor Ribeiro Sucupira <>
Sun Apr 27 09:28:05 CEST 2008


Hum... I see.
Maybe this other implementation?

floorDiv(A, B) ->
    case ((A < 0 andalso B >= 0) orelse (A >= 0 andalso B < 0))
andalso A rem B =/= 0 of
        true -> (A div B) - 1;
        false -> A div B
    end.

On Sat, Apr 26, 2008 at 11:06 PM, Dimitry Golubovsky
<> wrote:
> Igor,
>
>  Thanks for the suggestion, but it does not work as needed with large
>  numbers. I tried similar things just like floor(A/B) (floor/1 was
>  found somewhere on TrapExit).
>
>  Say we want to print a factorial of 40. Each digit is obtained by
>  taking a quot and rem from division by 10. What I compute is
>  equivalent to (show . fac) in Haskell
>
>  With your function instead of div, in Haskell compiled to Erlang:
>
>  11> hserl:hslist((hserl:force(hs_test1:main()))(40)).
>  "815915283247897600060660666066242068688062066800"
>
>  Same in ghci:
>
>  Prelude> let fac 1 = 1; fac n = n * fac (n - 1)
>  Prelude> (show . fac) 40
>  "815915283247897734345611269596115894272000000000"
>
>  And when I use the standard div, in Haskell compiled to Erlang:
>
>  13> hserl:hslist((hserl:force(hs_test1:main()))(40)).
>  "815915283247897734345611269596115894272000000000"
>
>  Thanks.
>
>
>  On Sat, Apr 26, 2008 at 7:59 PM, Igor Ribeiro Sucupira <> wrote:
>  > You could use, for example, the BIF trunc/1.
>  >  Something like this:
>  >
>  >  floorDiv(A, B) ->
>  >     Quotient = A / B,
>  >     Truncated = trunc(Quotient),
>  >     case Truncated > Quotient of
>  >         true -> Truncated - 1;
>  >         false -> Truncated
>  >     end.
>  >
>  >
>  --
>
>
> Dimitry Golubovsky
>
>  Anywhere on the Web
>



More information about the erlang-questions mailing list