What is "Luhn Algorithm"? ๐Ÿค”

What is "Luhn Algorithm"? ๐Ÿค”

ยท

2 min read

Do you know, how a website verifies the Card number (credit/debit) that you have entered while online payment or net banking? This is where the Luhn Algorithm works. Most credit cards and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from mistyped or otherwise incorrect numbers. It was designed to protect against accidental errors and not malicious attacks.

Steps involved in the Luhn Algorithm

  1. Starting from the rightmost digit, double the value of every second digit.
  2. If doubling of a number results in a two digit number i.e greater than 9(e.g., 6 ร— 2 = 12), then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), to get a single digit number.
  3. Now take the sum of all the digits.
  4. If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.

Below is the pictorial representation of the algorithm

algorithm.jpeg


Code Snippet

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

bool checkLuhn(string &card_no)
{
    //total_digits-> Variable to store length of the card number
    int total_digits = card_no.length();

    //sum-> Variable to store sum of double digit numbers
    //is_second-> Variable to check if odd place number or not
    int sum = 0, is_second = false;

    for (int i = total_digits - 1; i >= 0; i--) 
    {
        //converting character type to integer type
        //variable 'd' stores the integer equivalent
        int d = (int)card_no[i] - 48;

        if (is_second == true)
            d = d * 2;

        // adding two digits if there are
        // cases that make two digits after
        // doubling
        sum += d / 10; //ten's place
        sum += d % 10; //one's place

        //inverting this variable after every iteration
        is_second = !is_second;
    }

    //return true if number is divisible by 10
    return (sum % 10 == 0);
}

int main() {

    //variable to store user input card number
    string card_no;

    cout<<"Enter the card number to check if it is valid or not"<<endl;
    cin>>card_no;

    if (checkLuhn(card_no))
        printf("This is a valid card");
    else
        printf("This is not a valid card");

    return 0;
}

Enter the card number to check if it is valid or not
4137894711755904

Output
This is a valid card

Thanks for reading!๐Ÿ˜ƒ

PS: You can run this code on any IDE and play with the inputs. Do check for negative test case.

ย