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 [2025/10/27 20:20] (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; | ||
| + | } | ||
| </ | </ | ||
| Line 56: | Line 107: | ||
| 3. **Calculate the Checksum with the Luhn Algorithm**: | 3. **Calculate the Checksum with the Luhn Algorithm**: | ||
| - | - Apply the Luhn algorithm to calculate the checksum digit (the last digit), which will make the number valid. | + | * Apply the Luhn algorithm to calculate the checksum digit (the last digit), which will make the number valid. |
| === Example Code to Generate a Valid Card Number === | === Example Code to Generate a Valid Card Number === | ||
tanszek/oktatas/techcomm/luhn_algortithm_to_protect_credit_card_numbers.1730825266.txt.gz · Last modified: 2024/11/05 16:47 by knehez
