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.)


include "cowgol.coh";
 
sub check_isbn13(isbn: [uint8]): (r: uint8) is  
    var n: uint8 := 0;
    r := 0;
    loop    
        var c := [isbn];
        isbn := @next isbn;
        if c == 0 then break; end if;
        c := c - '0';
        if c <= 9 then
            r := r + c;
            n := n + 1;
            if (n & 1) == 0 then
                r := r + c * 2;
            end if;
        end if;
    end loop;
    if n == 13 and r%10 == 0 then
        r := 1;
    else
        r := 0;
    end if;
end sub;
 
var isbns: [uint8][] := {
    "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"
};
 
var result: [uint8][] := {": bad\n", ": good\n"};
 
var n: uint8 := 0;
while n < @sizeof isbns loop
    print(isbns[n]);
    print(result[check_isbn13(isbns[n])]);
    n := n + 1;
end loop;