This is the code I have written in c for the cs50 credit pset 1 problem.
I am checking the length of numbers entered, and the first digits (AMEX 15 digits, starts with 34 or 37; MC 16 digits, starts with 51/52/53/54/55; VISA, 13 or 16 digits, starts with 4) and then applying Luhn's algorithm to see if a card is valid (every other digit x 2, add the digits of those multiplications together, and then add to the total of the digits not x2. If = 20, card is valid).
The trouble I am having is with the Luhn's algorithm section; there keeps being errors, and every time I try to fix these, others appear.
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
long num = get_long("Number: ");
long number = num;
int digit;
int x;
int total_sum;
int num_digits = 0;
do
{
num_digits ++;
num /= 10;
}
while (num!=0);
//invalid if not the right number of digits
if ((num_digits != 13) && (num_digits != 15) && (num_digits != 16))
{
printf("INVALID\n");
}
else
{ //check algorithm
//if algorithm is false print invalid, otherwise the other lines of code become useful
while (x != 0)
{
x = number / 10 ;
int z = number % 10;
int y = x % 10; //number in second last position;
number = number/10;
if (y < 9)
{
total_sum = total_sum + 2*y + z;
}
else
{
total_sum = total_sum + (y % 10) + (y /10) + z;
}
}
if (total_sum % 10 != 0)
{
printf("INVALID\n");
}
//here, need to check luhn's algorithm. if false print invalid. if true, continue onwards.
else if (number / 10000000000000 == 34 || number / 100000000000 == 34)
{
printf("AMEX\n");
}
else if (number / 100000000000000 == 4 || number / 1000000000 == 4)
{
printf("VISA\n");
}
else if (number / 100000000000000 == 51 || number / 1000000000000 == 52 || number / 1000000000000 == 53 || number / 1000000000000 == 54 || number / 1000000000000 == 55 )
{
printf("MASTERCARD\n");
}
else
{
printf("INVALID\n");
}
}
}