Credit card checker using Luhn Algorithm.

The Luhn algorithm, also known as the modulus 10 or mod 10 algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, Canadian Social Insurance Numbers. The LUHN formula was created in the late 1960s by a group of mathematicians.

Consider the example of an account number “79927398713“. 


Step 1 – Starting from the rightmost digit, double the value of every second digit, 

Step 2 – If doubling of a number results in a two digit number i.e greater than 9(e.g., 6 × 2 = 12), then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), to get a single digit number.

Step 3 – Now take the sum of all the digits.

Step 4 – If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.

Since the sum is 70 which is a multiple of 10, the account number is possibly valid. 


Code for the same:

def validate_credit_card_number(card_number):
    num_str= str(card_number)[-2:-(len(str(card_number))+1):-2]
    num_str_remaining=str(card_number)[-1:-(len(str(card_number))+1):-2]
    sum_list=[]
    sum_list_remaining=[int(i) for i in num_str_remaining]

    for i in num_str:
        if 2*int(i)>9:
            digits=[ int(j) for j in str(2*int(i))]
            sum_list.append(sum(digits)) 
        else:
            sum_list.append(2*int(i))    

    return (sum(sum_list)+sum(sum_list_remaining))%10==0

card_number=4539869650133101 
result=validate_credit_card_number(card_number)
if(result):
    print("credit card number is valid")
else:
    print("credit card number is invalid")

Comments

Popular Posts