Checksums and early encryption

Weekly challenge 162 — 25 April 2022

Week 162 - 25 Apr 2022

Task 1

Write a script to generate the check digit of the given ISBN-13 code. Please refer to Wikipedia for more information.

Example 1: ISBN-13 check digit for '978-0-306-40615-7' is 7.

The ISBN checksum, or indeed any checksum, is there to provide an easy check for the plausibility of a multi-digit sequence. The same sort of technique is used for credit card numbers. The idea is that the commonest errors are (1) the alteration of a single digit or (2) the swapping of 2 consecutive digits, and both of these will usually change the check digit.

The check digit can obviously take only one of 10 different values and thus there is a 10% chance that a wrong set of digits will give the same checksum. However, by choosing different multipliers for consecutive digits the probability that swapping two consecutive digits yields the same checksum is much reduced - at the expense, of course, of slightly increasing the chance that a random error will result in an unchanged check digit.

The algorithm is pretty straightforward to code, and even in my rather wordy style is only 5 lines long.

#!/usr/bin/perl # Peter Campbell Smith - 2022-04-25 # PWC 162 task 1 use v5.28; use strict; use warnings; use utf8; my ($sum, $test, @digits, @multipliers, @tests); # data @tests = ('978-0-306-40615-7', '978-1-85345-445-5', '978-3-468-98143-2'); # multipliers of successive digits as defined @multipliers = qw(1 3 1 3 1 3 1 3 1 3 1 3); for $test (@tests) { # eliminate non-digits @digits = (); push @digits, $1 while $test =~ m|(\d)|g; # create weighted sum of first 12 digits $sum = 0; $sum += $digits[$_] * $multipliers[$_] for (0 .. 11); # and the 13th digit is 10 minus the sum, mod 10 say qq[ISBN-13 check digit for '$test' is ] . (10 - $sum % 10) . '.'; }

ISBN-13 check digit for '978-0-306-40615-7' is 7. ISBN-13 check digit for '978-1-85345-445-5' is 5. ISBN-13 check digit for '978-3-468-98143-2' is 2.

The content of this website which has been created by

Peter Campbell Smith is hereby placed in the public domain

Peter Campbell Smith is hereby placed in the public domain