In: Computer Science
IN C#
In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card numbers. The algorithm is useful to determine whether a card number is entered correctly or whether a credit card is scanned correctly by a scanner. Credit card numbers are generated following this validity check, commonly known as the Luhn check or the Mod 10 check, which can be described as follows (for illustration, consider the card number 4388576018402626): 1. Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number. 2. Now add all single-digit numbers from Step 1. 4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37 3. Add all digits in the odd places from right to left in the card number. 6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38 4. Sum the results from Step 2 and Step 3. 37 + 38 = 75 5. If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. For example, the number 4388576018402626 is invalid, but the number 4388576018410707 is valid. Write a program that prompts the user to enter a credit card number as a long integer. Display whether the number is valid or invalid. Design your program to use the following methods: Use STRING as an input. Add methods
The complete solution of your question given below,
using System;
using System.Collections;
class HelloWorld {
static void Main() {
string str;
int len,oddsum=0,evensum=0,i,j,sum=0;
Console.WriteLine("enter a credit card number");
str=Console.ReadLine();
len=str.Length;
if(len==16) // Check length of the CC number is 16 or not
{
for(i=len-1;i>=0;i--) // Reading number from right to left
{
int val = (int)Char.GetNumericValue(str[i]);
if(i%2!=0) // Find out the position of number is odd or even
{
oddsum=oddsum+val;
}
else
{
val=val*2; // Double the value of every second digit
if(val>9) // Check the result is two digit
{
String num=val.ToString();
int n1=(int)Char.GetNumericValue(num[0]);
int n2=(int)Char.GetNumericValue(num[1]);
int res=n1+n2;
evensum=evensum+res;
}
else
evensum=evensum+val;
}
}
sum=oddsum+evensum; // Sum the oddsum and evensum results
if(sum%10==0) //Check the result is divisible by 10 or not
Console.WriteLine("valid");
else
Console.WriteLine("invalid");
}
else
{
Console.WriteLine("Enter valid CC number");
}
}
}
note : Read the comments for better understanding of the solution