Luhn Algorithm
The Luhn Algorithm, also known as the modulus 10 or mod 10 algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers. It helps to detect accidental errors in the input data.
Here's a step-by-step explanation of the Luhn Algorithm:
Consider the example of an account number “79927398713“.
- Starting from the rightmost digit and moving left, double the value of every second digit.
- If the doubling results in a number greater than 9, then add the two digits.
Second digits from right most are 1, 8, 3, 2, 9
Doubling those digits give 2, 16, 6, 4, 18
Adding double digits give 2, 7, 6, 4, 9
- Sum all the digits, including both the untouched digits and the doubled digits.
Hence sum is 7 + 9 + 9 + 4 + 7 + 6 + 9 + 7 + 7 + 2 + 3 = 70
- If the total modulo 10 is equal to 0, then the number is valid according to the Luhn Algorithm.
70 % 10 = 0
package com.example.godel.service;
public class CardNumberValidation {
/**
* Validates the card number
* @param number
* @return true or false
*/
public boolean isValid(String number) {
int cardNumberLength = number.length();
boolean isSecond = false;
int i = cardNumberLength-1;
int sum = 0;
while(i >= 0) {
int currentNumber = number.charAt(i) - '0';
i--;
if (isSecond) {
currentNumber *= 2;
}
sum += currentNumber / 10;
sum += currentNumber % 10;
isSecond = !isSecond;
}
return (sum % 10 == 0);
}
}
Comments
Post a Comment