HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

Credit card validation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
creditvalidationcard

Problem

I started following Harvard's CS50 (Introduction to Computer Science) on edX, and as part of their Hacker edition set 1 was the following assignment:

I am supposed to write a program (in C), that takes as input a long long int from the user and proceeds to check whether the entered number is a valid credit card number. For the purposes of this assignment, I am only interested in Visa, American Express and MasterCard number formats. The validation is done with Luhn's algorithm.

```
/* This program checks whether an entered number is a valid
* credit card number (only American Express, Visa and
* MasterCard formats are supported).
*/

#include
#include
#include
#include

int main(void)
{
long long int credit_card;
int digits = 0;
string bank = "";

printf("Number: ");
credit_card = GetLongLong();

// calculate number of digits
for (long long int temporary = credit_card; temporary > 0;
temporary /= 10, digits++);

// check if number length corresponds to valid format
switch (digits)
{
case 13:
if ( (credit_card / (long long int) pow(10, digits - 1) ) == 4)
{
bank = "VISA";
break;
}

case 15:
if ( ( (credit_card / (long long int) pow(10, digits - 2)) == 34 ) ||
(credit_card / (long long int) pow(10, digits - 2)) == 37)
{
bank = "AMEX";
break;
}

case 16:
if ( ( (credit_card / (long long int) pow(10, digits - 2)) >= 51) &&
(credit_card / (long long int) pow(10, digits - 2)) <= 55)
{
bank = "MASTERCARD";
break;

}
else if ( (credit_card / (long long int) pow(10, digits - 1) ) == 4)
{
bank = "VISA";
break;
}
// sets bank to invalid if it doesn't satisfy any of the st

Solution

Avoid floating point

Actually I would advise the opposite of what @Xean said. I would completely remove all floating point from your program, including any calls to pow and log. I prefer your original loop to compute the number of digits.

The reason I don't like using floating point is that you might mysteriously get erroneous results due to roundoff errors. For example, on my computer, when I do this:

val = pow(9, 17);


I get this result, which is off by one:

16677181699666568 (actual value should be one higher)


For your program, you could either write a simple function to compute the powers of ten you need, or even hardcode the four values you need since you are only using powers 12, 13, 14, and 15.

Code Snippets

val = pow(9, 17);
16677181699666568 (actual value should be one higher)

Context

StackExchange Code Review Q#101059, answer score: 11

Revisions (0)

No revisions yet.