How do you do modulo or remainder in Erlang?

后端 未结 8 1810
悲哀的现实
悲哀的现实 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:32

    According to this blog post, it's rem.

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

    In Erlang, 5 rem 3. gives 2, and -5 rem 3. gives -2. If I understand your question, you would want -5 rem 3. to give 1 instead, since -5 = -2 * 3 + 1.

    Does this do what you want?

    mod(X,Y) when X > 0 -> X rem Y;
    mod(X,Y) when X < 0 -> Y + X rem Y;
    mod(0,Y) -> 0.
    
    0 讨论(0)
  • 2020-12-29 18:38
    mod(A, B) when A > 0 -> A rem B;
    mod(A, B) when A < 0 -> mod(A+B, B); 
    mod(0, _) -> 0.
    
    % console:
    3> my:mod(-13, 5).
    2
    
    0 讨论(0)
  • 2020-12-29 18:40

    The erlang modulo operator is rem

    Eshell V5.6.4  (abort with ^G)
    1> 97 rem 10.
    7
    
    0 讨论(0)
  • 2020-12-29 18:45

    I used the following in elixir:

    defp mod(x,y) when x > 0, do: rem(x, y);
    defp mod(x,y) when x < 0, do: rem(x, y) + y;
    defp mod(0,_y), do: 0
    

    Please don't downvote this because it's another language than the question. We all live the dream, because we all have the beam.

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

    The above Y + X rem Y seems to be wrong: either (Y + X) rem Y or Y + (X rem Y) yield incorrect results. Ex: let Y=3. If X=-4, the first form returns -1, if X=-3 the second form returns 3, none of which is in [0;3[.

    I use this instead:

    % Returns the positive remainder of the division of X by Y, in [0;Y[. 
    % In Erlang, -5 rem 3 is -2, whereas this function will return 1,  
    % since -5 =-2 * 3 + 1.
    
    modulo(X,Y) when X > 0 ->   
       X rem Y;
    
    modulo(X,Y) when X < 0 ->   
        K = (-X div Y)+1,
        PositiveX = X + K*Y,
        PositiveX rem Y;
    
    modulo(0,_Y) -> 
        0.
    
    0 讨论(0)
提交回复
热议问题