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


isbn13_check = proc (s: string) returns (bool)
    if string$size(s) ~= 14 then return(false) end
    if s[4] ~= '-' then return(false) end
    begin
        check: int := 0
        for i: int in int$from_to(1, 14) do
            if i=4 then continue end
            d: int := int$parse(string$c2s(s[i]))
            if i=2 cor (i>4 cand i//2=1) then d := d*3 end
            check := check + d
        end
        return(check//10 = 0)
    end except when bad_format: 
        return(false)
    end
end isbn13_check
 
start_up = proc ()
    po: stream := stream$primary_output()
    tests: array[string] := array[string]$
       ["978-1734314502",
        "978-1734314509",
        "978-1788399081",
        "978-1788399083"]
 
    for test: string in array[string]$elements(tests) do
        stream$puts(po, test)
        stream$puts(po, ": ")
        if isbn13_check(test)
            then stream$putl(po, "good")
            else stream$putl(po, "bad")
        end
    end
end start_up