Task

Validate the check digit of an ISBN-13 code:

   Multiply every other digit by  3.
   Add these numbers and the other digits.
   Take the remainder of this number after division by  10.
   If it is  0,   the ISBN-13 check digit is correct.


Use the following codes for testing:

   978-1734314502       (good)
   978-1734314509         (bad)
   978-1788399081       (good)
   978-1788399083         (bad)


Show output here, on this page



See also

   for details:   13-digit ISBN method of validation.       (installs cookies.)


MODULE ISBN;
FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length;
 
PROCEDURE validISBN(s: ARRAY OF CHAR): BOOLEAN;
    VAR total, i, length: CARDINAL;
BEGIN
    total := 0;
    length := Length(s);
    IF (length # 14) OR (s[3] # '-') THEN
        RETURN FALSE;
    END;
    FOR i := 0 TO length-1 DO
        IF i # 3 THEN
            IF (s[i] < '0') OR (s[i] > '9') THEN
                RETURN FALSE;
            ELSIF (i < 3) AND (i MOD 2 = 1) OR (i > 3) AND (i MOD 2 = 0) THEN
                total := total + 3 * (ORD(s[i]) - ORD('0'));
            ELSE
                total := total + ORD(s[i]) - ORD('0');
            END;
        END;
    END;
    RETURN total MOD 10 = 0;
END validISBN;
 
PROCEDURE check(s: ARRAY OF CHAR);
BEGIN
    WriteString(s);
    WriteString(': ');
    IF validISBN(s) THEN
        WriteString('good');
    ELSE
        WriteString('bad');
    END;
    WriteLn;
END check;
 
BEGIN
    check('978-1734314502');
    check('978-1734314509');
    check('978-1788399081');
    check('978-1788399083');
END ISBN.