How does modulus work exactly? [duplicate]
I know what modulus (%) does, it gives you the remainder. But how does it do that? I saw that it uses the formula: modulus = dividend - (dividend / divisor) * divisor 10%3 should give you 1 (10 being the dividend and 3 being the divisor) the forumla gives: 10-(10/3)*3 = 10-10 = 0 which is obviously wrong.
Then again, working with pure variables, dividend - ( dividend / divisor ) * divisor = dividend - dividend = 0
What am I doing wrong here? (Also, the form开发者_开发知识库ula is from a native from JASS, the language used in warcraft 3 games)
in the formula (dividend / divisor)
is an integer division evaluating to an integer.
So, 10-(10/3)*3 = 10 - 9 = 1
In many programming languages using C, C++, Java, etc. 10/3 would result in 3 because divisions are actually integer-divisions and the fractional part is truncated.
So, in other words n/d gives you only the quotient.
Now, from arithmetic we know that any positive integer n and any positive integer divider d, n can be represented as: n = q*d + r. If 0 ≤ r < n (and it can be proven that there is only one such positive r that is less than n), q is called the quotient and r is the called the remainder.
In these programming languages, n/d gives you q.
So, n - (n/d)*d = n - q*d = r, the remainder.
精彩评论