Introduction
The Luhn algorithm is a simple checksum formula used to validate various identification numbers, such as credit card numbers, IMEI numbers, and Canadian Social Insurance Numbers. It was created by IBM scientist Hans Peter Luhn in the 1950s. This algorithm helps detect accidental errors that may occur during the manual entry of these numbers.

In this article, we will learn how the Luhn algorithm works & will see its code implementation.
Overview of the algorithm:
The Luhn algorithm, also known as the modulus 10 or mod 10 algorithm, is a simple checksum formula that verifies the accuracy of an identification number. The algorithm performs a series of calculations on the digits of the number & determines if it is valid based on the result.
Let’s see how this algorithm works:
1. Start from the rightmost digit & move left, doubling the value of every second digit. If the doubled value is greater than 9, subtract 9 from the result.
2. Sum up all the digits, including the unmodified digits & the results from step 1.
3. If the total sum is divisible by 10, the number is valid according to the Luhn algorithm. Otherwise, the number is invalid.
For example, let's consider the number "7992739871". Applying the Luhn algorithm:
- Double every second digit from the right: 7 18 9 4 7 6 9 16 7 2
- Subtract 9 from any doubled digit greater than 9: 7 9 9 4 7 6 9 7 7 2
- Sum up all the digits: 7 + 9 + 9 + 4 + 7 + 6 + 9 + 7 + 7 + 2 = 67
- Since 67 is not divisible by 10, the number is invalid.
This algorithm is widely used to validate credit card numbers, IMEI numbers, & other identification numbers to catch accidental errors during manual entry or transmission.