Created
April 13, 2020 19:00
-
-
Save thegeorgeous/0dfd61b4fe88521be9299ad9c282ae65 to your computer and use it in GitHub Desktop.
Luhn Number generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
public class LuhnGenerator { | |
public static String generate(Integer len) { | |
Random rgen = new Random(); | |
Integer luhnNumber = rgen.nextInt(899999) + 100000; | |
String code = luhnNumber.toString(); | |
return code + generateCheckSum(code); | |
} | |
public static String generateCheckSum(String code) { | |
Integer codeLength = code.length(); | |
Integer luhnChecksum = 0; | |
Integer luhnCheckDigit; | |
for (Integer i = codeLength; i > 0; i--) { | |
String codeDigit = code.substring(i-1, i); | |
Integer luhnDigit = Integer.parseInt(codeDigit); | |
if (i % 2 == 0) { | |
luhnDigit *= 2; | |
if (luhnDigit > 9) { | |
luhnDigit -= 9; | |
} | |
} | |
luhnChecksum += luhnDigit; | |
} | |
luhnCheckDigit = (luhnChecksum * 9) % 10; | |
return luhnCheckDigit.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment