Skip to content

Instantly share code, notes, and snippets.

@cosminpopescu14
Created October 7, 2018 15:10
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 cosminpopescu14/ceb98b909aa69c7424d3deb8a8e4305c to your computer and use it in GitHub Desktop.
Save cosminpopescu14/ceb98b909aa69c7424d3deb8a8e4305c to your computer and use it in GitHub Desktop.
Implementation of Luhn algorithm
using System;
namespace Luhn
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(IsValid());
Console.ReadLine();
}
static bool IsValid(string cardNumber = "1111222233334444")
{
int sum = 0;
int numberOfDigits = cardNumber.Length;
int parity = (numberOfDigits - 1) % 2;
char[] digit = new char[] { '\0' };
for (int index = numberOfDigits; index > 0; index--)
{
digit[0] = cardNumber[index - 1];
int nDigit = int.Parse(digit);
if (parity == index % 2)
nDigit *= 2;
sum += nDigit / 10;
sum += nDigit % 10;
}
return 0 == sum % 10;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment