tanszek:oktatas:techcomm:luhn_algortithm_to_protect_credit_card_numbers
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
tanszek:oktatas:techcomm:luhn_algortithm_to_protect_credit_card_numbers [2024/11/05 16:47] – knehez | tanszek:oktatas:techcomm:luhn_algortithm_to_protect_credit_card_numbers [2024/11/12 12:06] (current) – [Steps of the Luhn Algorithm] knehez | ||
---|---|---|---|
Line 40: | Line 40: | ||
card_number = " | card_number = " | ||
print(" | print(" | ||
+ | </ | ||
+ | |||
+ | Here is a C implementation of the algorithm: | ||
+ | |||
+ | <sxh c> | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | |||
+ | // Function to validate a Visa card number using the Luhn Algorithm | ||
+ | int isValidVisaCard(const char* cardNumber) { | ||
+ | int length = strlen(cardNumber); | ||
+ | int sum = 0; | ||
+ | int isSecond = 0; | ||
+ | |||
+ | // Traverse the card number in reverse | ||
+ | for (int i = length - 1; i >= 0; i--) { | ||
+ | int digit = cardNumber[i] - ' | ||
+ | |||
+ | if (isSecond) { | ||
+ | // Double every second digit | ||
+ | digit *= 2; | ||
+ | if (digit > 9) { | ||
+ | // Subtract 9 if the doubled value is greater than 9 | ||
+ | digit -= 9; | ||
+ | } | ||
+ | } | ||
+ | |||
+ | // Add digit to the sum | ||
+ | sum += digit; | ||
+ | // Toggle the isSecond flag | ||
+ | isSecond = !isSecond; | ||
+ | } | ||
+ | |||
+ | // If the sum is divisible by 10, the card number is valid | ||
+ | return (sum % 10 == 0); | ||
+ | } | ||
+ | |||
+ | int main() { | ||
+ | char cardNumber[20]; | ||
+ | printf(" | ||
+ | scanf(" | ||
+ | |||
+ | if (isValidVisaCard(cardNumber)) { | ||
+ | printf(" | ||
+ | } else { | ||
+ | printf(" | ||
+ | } | ||
+ | |||
+ | return 0; | ||
+ | } | ||
</ | </ | ||
tanszek/oktatas/techcomm/luhn_algortithm_to_protect_credit_card_numbers.1730825266.txt.gz · Last modified: 2024/11/05 16:47 by knehez