-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathCredit.c
71 lines (70 loc) · 1.69 KB
/
Credit.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//Simple program to check wehther or not the credit card numbers are legit
#include <cs50.h>
#include <stdio.h>
int main(void)
{
//getting intial valid number
long number;
do
{
number = get_long("Number: ");
}
//normally the expression was while (number < 1000000000000 || number > 10000000000000000);
//but there was a problem with this, so I had to decrease the number
while (number < 1000000000 || number > 10000000000000000);
//calculating the number digits and getting to know the first 2 digits of the number
int digits = 2;
long strnumber = number;
while (strnumber > 100)
{
strnumber /= 10;
digits++;
}
//using Luhn's algorithm
int sum = 0, xsum = 0, extra;
for (int i = 0; i < digits; i++)
{
if (i % 2 == 0)
{
sum = sum + number % 10;
number /= 10;
}
else
{
if ((number % 10 * 2) > 9)
{
extra = number % 10 * 2;
xsum = xsum + extra % 10;
extra /= 10;
xsum += extra;
}
else
{
xsum = xsum + (number % 10 * 2);
}
number /= 10;
}
}
if ((sum + xsum) % 10 != 0)
{
printf("INVALID\n");
return 0;
}
//deciding which credit card company is it
if (strnumber == 34 || strnumber == 37)
{
printf("AMEX\n");
}
else if (strnumber > 50 && strnumber < 56)
{
printf("MASTERCARD\n");
}
else if (strnumber / 10 == 4 && digits > 12)
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}