Created
April 8, 2026 17:48
-
-
Save SeanFeldman/197fb33021108cfd2ed8496153c28001 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
| // dotnet run LuhnNumberGenerator.cs | |
| using System; | |
| const int DesiredLength = 11; // Change this to generate different lengths | |
| const int NumberToGenerate = 1; // How many numbers to generate | |
| if (DesiredLength < 2) | |
| { | |
| Console.WriteLine("Error: Length must be at least 2 (1 digit + 1 check digit)."); | |
| return; | |
| } | |
| Console.WriteLine($"Generating {NumberToGenerate} Luhn-valid numbers of length {DesiredLength}"); | |
| Console.WriteLine(new string('─', 50)); | |
| var rng = new Random(); | |
| for (var i = 1; i <= NumberToGenerate; i++) | |
| { | |
| var number = GenerateLuhnNumber(rng, DesiredLength); | |
| var isValid = ValidateLuhn(number); | |
| Console.WriteLine($" {i,2}. {number} ✓ Luhn={isValid}"); | |
| } | |
| Console.WriteLine(new string('─', 50)); | |
| // Sanity check: tamper with last digit to prove validation catches it | |
| var sample = GenerateLuhnNumber(rng, DesiredLength); | |
| var tampered = sample[..^1] + ((sample[^1] - '0' + 1) % 10); | |
| Console.WriteLine($"Sanity check:"); | |
| Console.WriteLine($" Original : {sample} Luhn={ValidateLuhn(sample)}"); | |
| Console.WriteLine($" Tampered : {tampered} Luhn={ValidateLuhn(tampered)}"); | |
| static string GenerateLuhnNumber(Random rng, int length) | |
| { | |
| Span<char> digits = stackalloc char[length]; | |
| // First digit: 1-9 (no leading zero) | |
| digits[0] = (char)('1' + rng.Next(9)); | |
| // Middle digits: 0-9 | |
| for (var i = 1; i < length - 1; i++) | |
| digits[i] = (char)('0' + rng.Next(10)); | |
| // Compute check digit | |
| digits[^1] = ComputeCheckDigit(digits[..^1]); | |
| return new string(digits); | |
| } | |
| static char ComputeCheckDigit(ReadOnlySpan<char> partial) | |
| { | |
| var sum = 0; | |
| var shouldDouble = true; | |
| for (var i = partial.Length - 1; i >= 0; i--) | |
| { | |
| var d = partial[i] - '0'; | |
| if (shouldDouble) | |
| { | |
| d *= 2; | |
| if (d > 9) d -= 9; | |
| } | |
| sum += d; | |
| shouldDouble = !shouldDouble; | |
| } | |
| return (char)('0' + (10 - sum % 10) % 10); | |
| } | |
| static bool ValidateLuhn(string number) | |
| { | |
| var total = 0; | |
| var alt = false; | |
| for (var i = number.Length - 1; i >= 0; i--) | |
| { | |
| var curDigit = number[i] - '0'; | |
| if (alt) | |
| { | |
| curDigit *= 2; | |
| if (curDigit > 9) curDigit -= 9; | |
| } | |
| total += curDigit; | |
| alt = !alt; | |
| } | |
| return total % 10 == 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment