How can I underflow a number in constant time O(1)?

Viewed 80

I want to create a "datatype", that does an underflow in constant time. So if you have 10 as an upper bound, and pass the value 12, it gives you 8.

In the following code, max is the upper entry bound for my value val.

while(val > max)
   val -= max;

Currently I have only this iterative code, which could be expressed with a modulo-operation. I just don't know how.

Example for 6 enter image description here

1 Answers

What's wrong with val = val % max ? (If anything, please show more counterexamples.)

UPDATE: assuming the Bound in image is the same thing as max variable it seems you want expression max - (val - 1) % (max + 1).

Related