Modulus division when first number is smaller than second number

僤鯓⒐⒋嵵緔 提交于 2019-11-30 01:14:04

问题


I apologize if this is a simple question but I'm having trouble grasping the concept of modulus division when the first number is smaller than the second number. For example when 1 % 4 my book says the remainder is 1. I don't understand how 1 is the remainder of 1 % 4.
1 / 4 is 0.25. Am I thinking about modulus division incorrectly?


回答1:


First, in Java, % is the remainder (not modulo) operator, which has slightly different semantics. That said, you need to think in terms of integer-only division, as if there were no fractional values. Think of it as storing items that cannot be divided: you can store zero items of size 4 in a storage of overall capacity one. Your remaining capacity after storing the maximum number of items is one. Similarly, 13%5 is 3, as you can fit 2 complete items of size 5 in a storage of size 13, and the remaining capacity is 13 - 2*5 = 3.




回答2:


If you divide 1 by 4, you get 0 with a remainder of 1. That's all the modulus is, the remainder after division.




回答3:


I am going to add a more practical example to what "Jean-Bernard Pellerin" already said.

It is correct that if you divide 1 by 4 you get 0 but, Why when you do 1 % 4 you have 1 as result?

Basically it is because this:

n = a / b (integer), and
m = a % b = a - ( b * n )

So,

 a    b    n = a/b  b * n  m = a%b
 1    4      0        0      1    
 2    4      0        0      2
 3    4      0        0      3
 4    4      1        0      0
 5    4      1        4      1

Conclusion: While a < b, the result of a % b will be "a"




回答4:


Another way to think of it as a representation of your number in multiples of another number. I.e, a = n*b + r, where b>r>=0. In this sense your case gives 1 = 0*4 + 1. (edit: talking about positive numbers only)




回答5:


I think you are confused between %(Remainder) and /(Division) operators.

When you say %, you need to keep dividing the dividend until you get the remainder 0 or possible end. And what you get in the end is called Remainder.

When you say /, you divide the dividend until the divisor becomes 1. And the end product you get is called Quotient




回答6:


Another nice method to clear things up, In modulus, if the first number is > the second number, subtract the second number from the first until the first number is less than the second.

17 % 5 = ?
17 - 5 = 12
12 % 5 = ?
12 - 5 = 7
7 % 5 = ?
7 - 5 = 2
2 % 5  = 2

Therefore 17 % 5, 12 % 5, 7 % 5 all give the answer of 2. This is because 2 / 5 = 0 (when working with integers) with 2 as a remainder.



来源:https://stackoverflow.com/questions/16311643/modulus-division-when-first-number-is-smaller-than-second-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!