0

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?

Oscar Sjöstedt
  • 289
  • 2
  • 10

2 Answers2

3

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;
MBo
  • 77,366
  • 5
  • 53
  • 86
  • Indeed, I was using Java, didn't know modulo's behavior varied! (a % b + b) % b is exactly the kind of solution I wanted, it's way cleaner. Thanks :) – Oscar Sjöstedt Aug 10 '20 at 20:29
1

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
Hawk
  • 2,042
  • 8
  • 16