How do you do modulo or remainder in Erlang?

后端 未结 8 1811
悲哀的现实
悲哀的现实 2020-12-29 17:56

I\'m brand new to Erlang. How do you do modulo (get the remainder of a division)? It\'s % in most C-like languages, but that designates a comment in Erlang.

Several

相关标签:
8条回答
  • 2020-12-29 18:48

    The accepted answer is wrong.

    rem behaves exactly like the % operator in modern C. It uses truncated division.

    The accepted answer fails for X<0 and Y<0. Consider mod(-5,-3):

    C:                     -5 % -3 == -2
    rem:                 -5 rem -3 == -2
    Y + X rem Y:    -3 + -5 rem -3 == -5 !! wrong !!
    

    The alternative implementations for the modulo operator use floored division and Euclidean division. The results for those are

    flooring division:   -5 mod -3 == -2
    euclidean division:  -5 mod -3 == 1
    

    So

    Y + X rem Y
    

    doesn't reproduce any modulo operator for X < 0 and Y < 0.

    And rem works as expected -- it's using truncated division.

    0 讨论(0)
  • 2020-12-29 18:50

    Erlang remainder not works with negative numbers, so you have to write your own function for negative parameters.

    0 讨论(0)
提交回复
热议问题