TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

What the heck is the value of “-n % n” in programming languages?

27 pointsby viiover 4 years ago

9 comments

brundolfover 4 years ago
Did I miss something? I got to the end and still don't know what -n % n actually accomplishes in practice, nor why it's mainly used in high-performance code
评论 #24924357 未加载
bertr4ndover 4 years ago
First it&#x27;s important to note that `n` is unsigned; if it&#x27;s signed the value of `-n % n` is 0, intuitively.<p>For unsigned n, the value is: MAX - n + 1 (where max is the maximum representable value in the type of n, e.g., UINT_MAX). The article explains this nicely. (I thought of 2&#x27;s complement when reasoning through this, but you don&#x27;t actually need to assume 2&#x27;s complement to follow the reasoning).<p>So, `-n % n` computes `(MAX - n + 1) % n` efficiently, without needing to worry about corner cases.<p>I suspect this is useful when you want to generate random numbers with a limited range, where the range doesn&#x27;t cleanly divide UINT_MAX. You need to cut a bit off the top from your underlying random number generator.
评论 #24924158 未加载
r-wover 4 years ago
<p><pre><code> let threshold = (0 &amp;- range) % range </code></pre> &gt; It is somewhat inconvenient that Swift forces us to write so much code, but we must admit that the result is probably less likely to confuse a good programmer.<p>Oh come on, it&#x27;s basically just one extra character.
kazinatorover 4 years ago
&gt; <i>warning C4146: unary minus operator applied to unsigned type, result still unsigned</i><p><pre><code> #ifdef _MSVC x = ~x + 1; &#x2F;&#x2F; &quot;Manual&quot; two&#x27;s complement to avoid warning. #else x = -x; &#x2F;&#x2F; Regular two&#x27;s complement any good C coder knows #endif</code></pre>
评论 #24925099 未加载
gumbyover 4 years ago
This only works on two&#x27;s complement machines. The C++ standard only required two&#x27;s complement with c++20.<p>That being said I am not sure I&#x27;ve ever programmed a one&#x27;s complement machine.
评论 #24926683 未加载
lights0123over 4 years ago
&gt; The ampersand (%) in this expression<p>s&#x2F;ampersand&#x2F;percent sign&#x2F;
评论 #24923690 未加载
musicaleover 4 years ago
It&#x27;s zero in Python, which makes perfect sense to me. Quotient is negative, remainder is zero.
评论 #24926284 未加载
hexoover 4 years ago
int main(void) { unsigned int n = 7; printf(&quot;%i&quot;, (-n % n)); return 0; }<p>this gives 4 :(
评论 #24924077 未加载
评论 #24924842 未加载
foldrover 4 years ago
Apart from the overall oddness of this, the result of applying the modulo operator to signed arguments is technically undefined behavior in C.
评论 #24924560 未加载