tanszek:oktatas:techcomm:luhn_algortithm_to_protect_credit_card_numbers

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
tanszek:oktatas:techcomm:luhn_algortithm_to_protect_credit_card_numbers [2024/11/05 16:47] kneheztanszek: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 = "4539148803436467" card_number = "4539148803436467"
 print("Valid" if luhn_check(card_number) else "Invalid") print("Valid" if luhn_check(card_number) else "Invalid")
 +</sxh>
 +
 +Here is a C implementation of the algorithm:
 +
 +<sxh c>
 +#include <stdio.h>
 +#include <string.h>
 +#include <ctype.h>
 +
 +// 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] - '0';
 +
 +        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("Enter the Visa card number: ");
 +    scanf("%19s", cardNumber);
 +
 +    if (isValidVisaCard(cardNumber)) {
 +        printf("The card number is valid.\n");
 +    } else {
 +        printf("The card number is invalid.\n");
 +    }
 +
 +    return 0;
 +}
 </sxh> </sxh>
  
tanszek/oktatas/techcomm/luhn_algortithm_to_protect_credit_card_numbers.1730825266.txt.gz · Last modified: 2024/11/05 16:47 by knehez