Luhn Algorithm

By Xah Lee. Date:

Coded this interview problem, in emacs lisp.

(defun my-sum-digits (str)
  "Take a string and sum the digits.
Return a number."
  (let (
        (ll (length str))
        (ii 0)
        (sumTotal 0)
        )
    (while (< ii ll)
      (setq sumTotal (+ sumTotal (string-to-number (substring str ii (+ ii 1) )) )  )
      (setq ii (1+ ii) )
      )
    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))
         (ii 0)
         (sumTotal 0))
    (when (not (= (% numLength 2) 0))
      (setq numToCheck (concat "0" numToCheck))
      (setq numLength (1+ numLength)))
    (while (< ii numLength)
      (let ((currentChar (substring numToCheck ii (+ ii 1))))
        (if (= (% ii 2) 0)
            (setq sumTotal (+ sumTotal (string-to-number currentChar)))
          (setq sumTotal (+ sumTotal
                            (my-sum-digits (number-to-string (* (string-to-number currentChar) 2)))))))
      (setq ii (1+ ii)))
    (if (string-equal (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#.