The most common use of such a design is to make sure that the result is non-negative. The operator% standard behaves differently for positive and negative arguments: for example, 4%3==1 , but (-2)%3==-2 , while you can expect (-2)%3==1 and (-2)/3==-1 , which is mathematically more correct.
This behavior can often cause problems when using modular arithmetic, and this mod add trick is often used to obtain a mathematically more correct non-negative result. Instead of just writing a%b , if a can be negative, (a%b+b)%b written.
However, using it in code in your question is strange. In this case, it is easier to assume that a is positive before calling the power function from the main code (for example, by making a main call, for example, power((a%mod+mod)%mod, b) ). Probably, the author simply wanted to gain additional confidence in the correctness, although he was not needed.
source share