룬 알고리즘(Luhn algorithm)은 신용카드 번호 검증에 사용되는 알고리즘이다.

이 알고리즘은 지식재산권의 보호기간이 끝난 퍼블릭 도메인 저작물에 속하며 오늘날 널리 사용되고 있다. ISO/IEC 7812-1에 규정되어 있다.[1]

구현 예 편집

의사 코드 편집

  function checkLuhn(string purportedCC) {
    int sum := integer(purportedCC[length(purportedCC)-1])
    int nDigits := length(purportedCC)
    int parity := nDigits modulus 2
    for i from 0 to nDigits - 2 {
        int digit := integer(purportedCC[i])
        if i modulus 2 = parity
            digit := digit × 2
        if digit > 9
            digit := digit - 9 
        sum := sum + digit
    }
    return (sum modulus 10) = 0
  }

C 편집

  #include <stdlib.h> // atoi
  #include <string.h> // strlen
  #include <stdbool.h> // bool

  bool checkLuhn(const char *pPurported)
  {
    int nSum       = 0;
    int nDigits    = strlen(pPurported);
    int nParity    = (nDigits-1) % 2;
    char cDigit[2] = "\0";
    for (int i = nDigits; i > 0 ; i--)
    {
      cDigit[0]  = pPurported[i-1];
      int nDigit = atoi(cDigit);

      if (nParity == i % 2)
        nDigit = nDigit * 2;

      nSum += nDigit/10;
      nSum += nDigit%10;
    }
    return 0 == nSum % 10;
  }

각주 편집