Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
The Math Trick Hidden in Your Credit Card Number (scientificamerican.com)
5 points by sonabinu 56 days ago | hide | past | favorite | 3 comments


Expressed in Haskell:

    import Data.Char

    card = "4024 6072 3695 0748"

    cardDigits = map digitToInt . filter (not . isSpace)

    doubleDigitSum d = 2 * d - if d<5 then 0 else 9

    doubleEveryOther = reverse . zipWith ($) (cycle [doubleDigitSum,id]) . reverse
   
    main = let
        cd = cardDigits $ card
        sd = sum . doubleEveryOther . init $ cd
        checkDigit = (- (sd + last cd)) `mod` 10
      in print checkDigit


I'm not conversant in Haskell, but this probably won't work on American Express card numbers - they have 15 digits, the final digit is still the Luhn checksum.

I did credit card processing 20 years ago - AmEx was very often the fly in the ointment.


The above code should work for any number of digits. It follows the spec given in the article, specifically:

    1. Write out all but the last digit of the card number.

    2. Write out all but the last digit of the card number.

    3. Starting from the right, double every other number.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: