-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathluhn.c
70 lines (53 loc) · 1.29 KB
/
luhn.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
/**
* The Luhn algorithm or Luhn formulam is a simple checksum formula
* used to validate a variety of identification numbers, such as
* credit card numbers, IMEI numbers etc.
*
* https://en.wikipedia.org/wiki/Luhn_algorithm
*/
#include <string.h>
#include <stdlib.h>
#include <assert.h>
int *get_array(char *str, int len)
{
int *arr = (int *) malloc(len * sizeof(int));
for (int i = 0; i < len; i++) {
arr[i] = str[i] - '0';
}
return arr;
}
int array_sum(int *arr, int len)
{
int sum = 0;
for (int i = 0; i < len; i++) {
sum += arr[i];
}
return sum;
}
int luhn_check_sum(char *str)
{
int len = (int) strlen(str);
int *arr = get_array(str, len);
for (int i = len - 1; i >= 0; i -= 2) {
int multiple = arr[i] * 2;
if (multiple > 9) {
multiple -= 9;
}
arr[i] = multiple;
}
int sum = array_sum(arr, len);
return sum * 9 % 10;
}
int main()
{
char *test_card_numbers[] = {
"601100099013942", "37828224631000",
"37144963539843", "555555555555444",
"501971701010374", "552263411203590"
};
int check_bits[] = {4, 5, 1, 4, 2, 6};
for (int i = 0; i < 6; i++) {
assert(check_bits[i] == luhn_check_sum(test_card_numbers[i]));
}
return 0;
}