Practical 7

Exercise 1

It is easy to make a mistake typing a sequence of numbers. Many ID numbers include one or more "check digits" to help protect against typing errors. The digit(s) can be calculated in a number of ways.

One popular method involves the following steps,

  1. the sum of the digits in the even positions
  2. the sum of the digits in the odd positions
  3. add three times the sum of the odd digits to the sum of the even digits
  4. the remainder of this number when dividing by ten
  5. subtracting this from nine gives the magic number
eg. calculate the check digit for the sequence 4561232

even sum: 3+1+5 = 9

odd sum: 2+2+6+4 = 14

combined sum: 3*14+9 = 51

remainder: 51%10 = 1

check digit: 9-1 = 8

The final number would then usually be written as 45612328 (10*4561232+8)

To get the digit in any position we can do an integer divide by 10(col-1) and find the remainder when dividing by 10,

eg. find the digit in column 3 of the number 4561232,

divide by 10^(col-1) : 4561232 / 10^2 = 4561232 / 100 = 45612

find the remainder dividing this by 10 : 45612 % 10 = 2

Exercise 2