Sign in Join
Wiki copytemporary

Luhn algorithm

English · Français

The Luhn algorithm created by Hans Peter Luhn. It is specified in ISO/IEC 7812-1. It is used by e.g. some credit card.

pascal
function LuhnAlgorithmCheckDigit(const s:string):integer;
var
  l, i, sum, deo : integer;
begin
  l := length( s );
  sum := 0;
  for i := l downto 1 do
    begin
      if odd(i) then sum := sum + StrToInt(s[i])
      else
        begin
          deo :=  StrToInt(s[i]) * 2 ;
          if deo  > 9 then deo := deo mod 10 + 1;
          sum := sum + deo;
        end;
    end;
  result := 10 - sum mod 10;
end;

function isLuhnValid( const s : string ): boolean;
var
  i, l :integer;
begin
  l := length( s );
  i := LuhnAlgorithmCheckDigit( copy( s, 1, l-1) );
  result :=  i  = StrToInt( s[ l ] );
end;

From the Free Pascal wiki, page "Luhn algorithm", as it stood on 2020-02-19 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 1, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.