Wednesday, 13 April 2016

How to use Luhn algorithm ?


 /**
  * Generation of Valid Number using Luhn Algorithm.
  * 1. Find the length of the number.
  * 2. Find the characters one by one and parse them into int.
  * 3. Double the alternate digits from right to left .
  * 4. For any digits that thus become 10 or more,

  *      Add their digits together.
  *      For example, 1111 becomes 2121, while 8763 becomes 7733 

  *      (from (1+6)=7 and (1+2)=3).
  * 5. Sum all the digits.
  * 6. If sum modulo 10 is 0,
  *      Add check sum digit as 0.
  * 7. else
  *      Find checksum digit (Multiply sum by 9 and find modulo by 10)
  *
  * @param number  Number of which we have to generate the checksum    

  * @return checkSumdigit Generated checksum digit
  */

  public static String generateValidNumberUsingLuhnAlgo(String number) {
     int sum = 0;
     boolean alternate = true;


     // Iterate the number by each digit from right to left
     for (int i = number.length() - 1; i >= 0; i--) {
         // get the digit
         int n = Integer.parseInt(number.substring(i, i + 1));
         /* for each alternate (even position) number, */
         if (alternate) {
             /* double the digit */
             n *= 2;
             /* if the value (after double) is in two digits */
             if (n > 9) {
                  /* Add both digits to make single digit */
                  n = (n % 10) + 1;
             }
         }


         /* Add the calculated digits */
         sum += n;
         alternate = !alternate;
     }

     /* default value for checksum */
     byte checkSumDigit = 0;
     /* Check modulo of the sum of digits */
     if((sum%10) == 0) {

        LOGGER.info("Number is valid according to LUHN algorithm. Adding default checksum: 0");    
     } else {
        /* Multiply the sum by 9 ,then find the modulo by 10 */
        checkSumDigit = (byte) ((sum*9) % 10);
        LOGGER.info("Generated checksum digit is: "+checkSumDigit);
     }

     return number + checkSumDigit;
  }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.