The “Get a Hint” posting for this exercise was closed to new questions, so I thought I would ask this here. I’m terrible at math, and am having a lot of trouble understanding how remainders work and why exactly they are used in code. Can someone please explain this to me?
Well, let’s forget the theory and have a look at a few examples
10 % 3 = 1
Why?
School maths:
10 / 3 = 3.3333333
Comp maths:
10 / 3 = 3
Okay, so 3 * 3 = 9, right? Now we take the original number which was 10 - 9, what’s the result? It’s 1 which is our reminder. In other words 10 % 3 = 1 ( give me the remainer of 10 % 3 )
7 % 2 = 1
School maths:
7 / 2 = 3.5
Comp maths:
7 / 2 = 3
3 * 2 is 6. But our original number was 7. So, we take our original number - what we have got, which is 6. Thus, 7 - 6 = 1 and that’s our remainder.
ps: for haters, I know that you’ll get different results based on the programming language you’re using, specifically, whether you’re working with ints/floats (doubles)
One possible use of the modulo, or remainder, operation is to “wrap around” to the beginning of an array when you reach its end. Consider this code:
const arr = [1, 2, 3]
const arrLength = arr.length
for (let i = 0; i < 6; i++) {
const remainder = i % arrLength
console.log(`i = ${i}, remainder = ${remainder}`)
console.log(`arr[remainder] = ${arr[remainder]}`)
}
This prints:
i = 0, remainder = 0
arr[remainder] = 1
i = 1, remainder = 1
arr[remainder] = 2
i = 2, remainder = 2
arr[remainder] = 3
i = 3, remainder = 0
arr[remainder] = 1
i = 4, remainder = 1
arr[remainder] = 2
i = 5, remainder = 2
arr[remainder] = 3
You can see that, even though i continues to increase, the remainder resets itself after reaching a multiple of the array’s length. In that way, you can continue to wrap around the array without worrying about resetting or decrementing i.
Briefly the remainder is what’s left after division - it’s a little complicated in javascript because numbers in javascript are real numbers - so 7 is actually 7.0 - 7 is the whole or integer part and 0.0 is the fractional part
Math.floor returns the integer part of positive numbers - Math.floor(7) is 7 and Math.floor(7.3) is 7 and Math.floor(7.9) is 7
So 7 / 2 is 3.5 - so 7 goes into 2 three times evenly - we say 3 is the quotient of 7 / 2 - we can get the quotient by applying Math.floor(7/2)
What about the remainder - is it 0.5? It is - but we are often interested in the integer remainder - one way to get the integer remainder is to remove the whole multiple of 2 from 7 - what’s left is a whole number too - so it’s 7 - 2*3 which is 1
This operation of subtracting the whole multiple of the divisor from the dividend is called modulo or remainder and has the % operator in javascript