Luhn algorithm

From Free Pascal wiki
Jump to navigationJump to search

English (en) français (fr)

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.

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;