Luhn Algorithm

By Xah Lee. Date:

Coded this interview problem, in emacs lisp.

(defun sum-digits (str)
  "Take a string and sum the digits.
Return a number."
  (let (
        (ll (length str))
        ($i 0)
        (sumTotal 0)
        )
    (while (< $i ll)
      (setq sumTotal (+ sumTotal (string-to-number (substring str $i (+ $i 1) )) )  )
      (setq $i (1+ $i) )
      )
    sumTotal
    ))

(defun luhn10-valid-p (creditCardString)
  "Return t if creditCardString passes Luhn algorithm, else `nil'."
  (interactive)
  (let* (
         (checkDigit (substring creditCardString -1 ) )
         (numToCheck (substring creditCardString 0 -1) )
         (numLength (length numToCheck) )
         ($i 0)
         (sumTotal 0)
         )
    (when (not (= (% numLength 2) 0) )
      (setq numToCheck (concat "0" numToCheck) )
      (setq numLength (1+ numLength) )
      )
    (while (< $i numLength)
      (let (
            (currentChar (substring numToCheck $i (+ $i 1 )) )
            )
        (if (= (% $i 2) 0)
            (setq sumTotal (+ sumTotal (string-to-number currentChar) ) )
          (setq sumTotal (+ sumTotal
                            (sum-digits (number-to-string (* (string-to-number currentChar) 2))) ) ) ) )
      (setq $i (1+ $i) )
      )
    (if (string= (substring (number-to-string (* sumTotal 9)) -1) checkDigit) t nil ) ))

It's not the full interview problem, but just parts that i can give away.

This is Luhn algorithm. Basically, it verifies that a credit card number or such is valid in some minimal sense.

On Wikipedia, they have implementation in Python, Ruby, PHP, JavaScript, PowerShell, C#.