selective-php / luhn

Luhn (Modulo 10 or mod 10 algorithm) for PHP
MIT License
10 stars 5 forks source link

Luhn algorithm implenetation discussion #1

Closed peter279k closed 5 years ago

peter279k commented 5 years ago

It looks like the Luhn algorithm has the two approaches.

The first approach is as follows:

Assume an example of an account number "7992739871" that will have a check digit added, making it of the form 7992739871x:

圖片

The sum of all the digits in the third row is 67+x.

The check digit (x) is obtained by computing the sum of the other digits (third row) then subtracting the units digit from 10 (67 => Units digit 7; 10 − 7 = check digit 3). In algorithm form:

The second approach is as follows:

(Alternative method) The check digit (x) is obtained by computing the sum of the non-check digits then computing 9 times that value modulo 10 (in equation form, ((67 × 9) mod 10)). In algorithm form:

It seems that we use the first approach to implement this algorithm.

I don't have the experiment to evaluate which these two approaches are faster.

Reference: Luhn_algorithm

peter279k commented 5 years ago

The algorithm implementation sounds good, and it doesn't have any issue when working on the unit tests.

This issue will be closed.