-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathluhn.c
51 lines (47 loc) · 1.26 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
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
// Luhn checksum calculation
bool luhnVerify(const char* ccNumber) {
int nDigits = 0, sum = 0, alt = 0;
while (ccNumber[nDigits]) nDigits++;
for (int i = nDigits - 1; i >= 0; i--) {
int digit = ccNumber[i] - '0';
if (alt) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
alt = !alt;
}
return (sum % 10 == 0);
}
// Generate valid Luhn number
void luhnGenerate(char* ccNumber, int length) {
srand(time(0));
for (int i = 0; i < length - 1; i++) {
ccNumber[i] = (rand() % 10) + '0';
}
ccNumber[length - 1] = '\0';
// Calculate check digit
int sum = 0, alt = 1;
for (int i = length - 2; i >= 0; i--) {
int digit = ccNumber[i] - '0';
if (alt) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
alt = !alt;
}
int checkDigit = (10 - (sum % 10)) % 10;
ccNumber[length - 2] = checkDigit + '0';
}
int main() {
char ccNumber[17];
luhnGenerate(ccNumber, 16);
printf("Generated CC Number: %s\n", ccNumber);
printf("Verification: %s\n", luhnVerify(ccNumber) ? "Valid" : "Invalid");
return 0;
}