Skip to content

Instantly share code, notes, and snippets.

@thegeorgeous
Created April 13, 2020 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thegeorgeous/0dfd61b4fe88521be9299ad9c282ae65 to your computer and use it in GitHub Desktop.
Save thegeorgeous/0dfd61b4fe88521be9299ad9c282ae65 to your computer and use it in GitHub Desktop.
Luhn Number generator
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