Fundamentals of Programming: Modulo arithmetic
Modular arithmetic is all about finding the remainder from long division (MOD), and the total number of times that a number goes into a division (DIV). Let's take a look at a quick example of 10 divided by 7 (you might want to remind yourself about long division):
1 r 3 7)10 7 3
Hopefully that wasn't too hard. We now need to introduce some terminology, MOD and DIV:
- MOD = finds the remainder from long division i.e. 10 MOD 7 = 3
- DIV = finds the number of divides in long division i.e. 10 DIV 7 = 1
Exercise: MOD and DIV
Try these examples, working out the MOD and DIV of each: 7 / 2
Answer : MOD = 1 DIV = 3 17 / 5
Answer : MOD = 2 DIV = 3 8 / 2
Answer : MOD = 0 DIV = 4 6 / 9
Answer : MOD = 6 DIV = 0 (9 does not divide into 6 at all!) Now try these explicit calculations: 11 MOD 8
Answer : = 3 8 MOD 4
Answer : = 0 6 DIV 5
Answer : = 1 600 DIV 20
Answer : = 30 |
Hopefully you are now pretty good with MOD and DIV, but what exactly is the point of all this? A very common example in past exam paper has been using the MOD and DIV to work out a binary equivalent of a denary number.
Note that Visual Basic does not have a DIV function and uses A\B instead |
Example: Converting Denary to Binary using DIV
sub convertDtoB(byVal base10 as integer) dim base2(7) as integer 'create an array to store the binary dim temp as integer = base10 for i = 7 to 0 step -1 'loop through each binary bit starting from the biggest value base2(i) = temp \ (2^i) 'temp DIV 2^i temp = temp MOD 2^i next console.write(base10 & " in binary = ") for i = 7 to 0 step -1 'loop through each binary bit starting from the biggest value console.write(base2(i)) next end sub Try the code out and see if it works. Try to write a trace table and see how it works for the number 67 (again another popular question in exams): Answer :
Output: 67 in binary = 01000011 |
Another common use is in finding out whether a number is odd or even using the MOD function. We know that MOD returns the remainder from a division sum. So for example 4 MOD 2 = 0, 5 MOD 2 = 1, 6 MOD 2 = 0 and so on. By modding something with 2 we can work out whether it is odd or not due to the return value.
Example: Finding out if a number is Odd using MOD
Dim testNum as Integer Dim temp as Integer console.writeline("please insert a number to test:") testNum = console.readline() If testNum MOD 2 = 0 Then Console.Writeline("The number is even") Else Console.Writeline("The number is odd") End If |