Modulo operation with negative numbers

前端 未结 12 1649
旧巷少年郎
旧巷少年郎 2020-11-22 06:10

In a C program i was trying the below operations(Just to check the behavior )

 x = 5 % (-3);
 y = (-5) % (3);
 z = (-5) % (-3); 

printf(\"%d ,%d ,%d\", x, y         


        
12条回答
  •  庸人自扰
    2020-11-22 06:40

    I don't think there isn't any need to check if the number is negative.

    A simple function to find the positive modulo would be this -

    Edit: Assuming N > 0 and N + N - 1 <= INT_MAX

    int modulo(int x,int N){
        return (x % N + N) %N;
    }
    

    This will work for both positive and negative values of x.

    Original P.S: also as pointed out by @chux, If your x and N may reach something like INT_MAX-1 and INT_MAX respectively, just replace int with long long int.

    And If they are crossing limits of long long as well (i.e. near LLONG_MAX), then you shall handle positive and negative cases separately as described in other answers here.

提交回复
热议问题