Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • Nitpick: It actually won't vectorize because there's generally no SIMD support for modulus. Commented Feb 21, 2013 at 8:46
  • 1
    Would it be more efficient to factor the n out into a template? In the case that the function cannot be inlined, the compiler may be able to play some tricks to improve performance. Commented Feb 21, 2013 at 9:02
  • Oops, you're right about the abs(), I've edited it out of my question. Commented Feb 21, 2013 at 10:32
  • 1
    Notice that for (-3 mod 3) using (i % n) + (n * (i < 0)) or (i % n) + (i < 0 ? n : 0), the result is 3: (-3 % 3) == 0 and (3 * (-3 < 0)) == 3, probably not the desired result. Commented Jun 20, 2013 at 22:57
  • 1
    One problem is if n is negative, then the module becomes negative... This instead seem to work: return (i % n + std::abs(n)) % n; Commented Mar 8, 2017 at 15:14