Reputation: 299
I need to make a function f(a,b)
that will give the following results:
f(0, 3) = 0
f(1, 3) = 1
f(2, 3) = 2
f(3, 3) = 0
f(4, 3) = 1... (this works exactly like a%b)
However it should also follow this pattern for negative numbers:
f(-4, 3) = 2
f(-3, 3) = 0
f(-2, 3) = 1
f(-1, 3) = 2
f( 0, 3) = 0
I currently found this solution:
x = a % b
return a < 0 && mod != 0 ? mod + b : mod;
However this feels way too complicated and slow for what I'm trying to achieve. Isn't there a simpler way to generate a sequence similar to modulo that continues for negative values?
Upvotes: 0
Views: 167
Reputation: 2142
This is not a general solution for any b
, but if you need just to wrap around an array from both sides and you are decrementing the index by 1 (or by at most a
) a valid and even shorter solution for any b >= -a
is:
(a + b) % b
Upvotes: 1
Reputation: 80187
Modulo operation behavior depends on programming language - see table here
For example, in Python print(-4 % 3)
gives 2
Seems you are using C-like language, where remainder has the same sign as dividend. In this case you can use such formula (ideone)
(a % b + b) % b
Also the only comparison is enough to correct negative value (so avoiding double %
)
rem = a % b;
if (rem < 0) rem += b;
Upvotes: 3