-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcredit.c
61 lines (55 loc) · 1.44 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
#include <cs50.h>
#include <stdio.h>
void print_credit_card_brand(long long ccn);
bool check_validity(long long credit_card_number);
int find_lenght(long long n);
bool checksum(long long ccn);
int main(void)
{
long long credit_card_number;
do
{
credit_card_number = get_long_long("Number: ");
} while (credit_card_number < 0);
if (check_validity(credit_card_number) == true)
print_credit_card_brand(credit_card_number);
else
printf("INVALID\n");
}
bool check_validity(long long credit_card_number)
{
int len = find_lenght(credit_card_number);
return (len == 13 || len == 15 || len == 16) && checksum(credit_card_number);
}
int find_lenght(long long n)
{
int len;
for (len = 0; n != 0; n /= 10, len++);
return len;
}
bool checksum(long long ccn)
{
int sum = 0;
for (int i = 0; ccn != 0; i++, ccn /= 10)
{
if (i % 2 == 0)
sum += ccn % 10;
else
{
int digit = 2 * (ccn % 10);
sum += digit / 10 + digit % 10;
}
}
return (sum % 10) == 0;
}
void print_credit_card_brand(long long ccn)
{
if ( (ccn >= 34e13 && ccn < 35e13) || (ccn >= 37e13 && ccn < 38e13) )
printf("American Express\n");
else if (ccn >= 51e14 && ccn < 56e14)
printf("Mastercard\n");
else if ( (ccn >= 4e12 && ccn < 5e12) || (ccn>= 4e15 && ccn < 5e15) )
printf("VISA\n");
else
printf("INVALID\n");
}