-
Notifications
You must be signed in to change notification settings - Fork 1
/
credit.c
135 lines (121 loc) · 2.87 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
string determineCompany(long number);
int validateNumber(long number);
int main(void)
{
long number;
string res = "";
//getting the creditcard number
number = get_long("Number: ");
//first check if length is ok
if (number > pow(10, 12))
{
//check for company
res = determineCompany(number);
if (!strcmp(res, "INVALID"))
{
printf("%s\n", res);
return 0;
}
}
else
{
printf("INVALID\n");
return 0;
}
//calculating checksum
int checksum = validateNumber(number);
if (checksum)
{
res = "INVALID";
}
//printing the result
printf("%s\n", res);
}
//determines the company given from ots starting
string determineCompany(long number)
{
long tmp = number;
string res = "INVALID";
while (tmp >= 100)
{
tmp /= 10;
}
if (tmp > 30)
{
switch (tmp)
{
case 34:
case 37:
res = "AMEX";
break;
case 51:
case 52:
case 53:
case 54:
case 55:
res = "MASTERCARD";
break;
default:
{
tmp /= 10;
if (tmp == 4)
{
res = "VISA";
}
}
break;
}
}
return res;
}
int validateNumber(long number)
{
//length calculation from: https://stackoverflow.com/questions/3068397/finding-the-length-of-an-integer-in-c
int length = (int)floor(log10(labs(number)));
//creating char array for iterating
char tmp[length];
sprintf(tmp, "%ld", number);
int other = 0, even = 0;
bool switcher = false;
//iterating from last to first
for (int idx = length; idx >= 0; idx--)
{
//check which case we need to process
if (switcher)
{
//getting int of char, times 2
int i = ((int)tmp[idx] - 48) * 2;
if (i > 9)
{
//if we got a 10 or higher we need to sum up ech digit
int buff_len = (int)floor(log10(labs(i))) + 1;
//creating new string for iterating
char buff[buff_len];
sprintf(buff, "%i", i);
//summing those up
for (int idy = 0; idy < buff_len; idy++)
{
other += ((int)buff[idy] - 48);
}
}
else
{
//summing up
other += i;
}
}
else
{
//summing up
even += ((int)tmp[idx] - 48);
}
//siwtch mode
switcher = !switcher;
}
return (other + even) % 10;
}