# [ACCEPTED]-real modulo operator in C/C++?-modulo

Accepted answer

There is no simple way to do it, however 5 it is more efficient if you create a two-line 4 solution, and spare a multiplication plus 3 determining `n`

.

```
inline int modulo(int a, int b) {
const int result = a % b;
return result >= 0 ? result : result + b;
}
```

Also, if you need to work correctly 2 for negative `b`

numbers as well, add to the 1 beginning:

```
if(b < 0) return modulo(-a, -b);
```

I would suggest a function like the one 5 above, but using `inline int modulo(int a, int b) {}`

(just as if the operator 4 existed in C++). Personnally I don't use 3 negative numbers often, and still think 2 you should keep `%`

whenever your code doesn't 1 use negative numbers.

Source:
stackoverflow.com

More Related questions

Cookie Warning

We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.