Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The Luhn Algorithm in C#
private static bool PassesLuhnTest(string cardNumber)
{
ReadOnlySpan<char> value = cardNumber;
var sum = 0;
var isDouble = false;
for (var i = value.Length - 1; i >= 0; i--)
{
int digit;
if (value[i] >= 48 && value[i] <= 57)
{
digit = value[i] - '0';
if (isDouble && (digit *= 2) > 9)
{
digit -= 9;
}
sum += digit;
isDouble = !isDouble;
}
}
return sum % 10 == 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment