For people building an e-commerce website, a payment portal from scratch, here's some thing which you'll find useful! No plugins required!

This is the **luhn algorithm** or **luhn formula** that checks if the credit card number is valid or not. You'll find this built-in validator in almost all payment processing platforms, like *Stripe*, *Paypal* to name a few.

The algorithm works this way:

- Starting from the second last digit, moving left double the value of every second digit.
- If the doubled result is greater than 9, subtract 9 from the doubled result
- Find sum all the digits
- Take the modulo 10 of the sum and if it equates to 0, then the number is valid according to the algorithm.

Take 79927398713 as an example, walkthrough of the algorithm is as follows:

|7|9|9|2|7|3|9|8|7|1|3|

- |7|
**18**|9|**4**|7|**6**|9|**16**|7|**2**|3| - |7|
**9**|9|4|7|6|9|**7**|7|2|3| - Sum of all digits = 70
- 70%10 = 0 Therefore, valid number.

Here's a javascript implementation depicting use of map and reduce. You can try in your favourite language as well!

```
function luhn(no){
no = no.toString();
arr = no.split('').map(x=>parseInt(x));
arr.reverse();
rArr = rArr.map(function(x,index){
if(index%2!=0){
if(x*2 >= 10) x = x*2 - 9;
else x = x*2;
}
return x;
});
sum = rArr.reduce((accu,curr)=>accu+curr);
if(sum%10==0) return true;
return false;
}
```

If you wish to know more about this algorithm, you can read more about this here.

Posted on by:

### Divyajyoti Ukirde

I'm currently ðŸŒ± learning and ðŸ” working on the Javascript Ecosystem. ðŸ˜„ Pronouns: she/her âš¡ Fun fact: I have a Computer Engineering background but the whole credit goes to Google and Stack Overflow

## Discussion

Ported to clojure

How about with some Method Chaining. :)

## Source code:

gist.github.com/funfunction/637732...

Yup, looks better! :)

Interesting.

Nevertheless, I've heard that credit card numbers means something (first ones determine if it a mastercard or visa).

But I don't know what all the numbers mean.

Do you know this ? Or where we can find this information ?

Cheers

stackoverflow.com/questions/72768/...

StackOverflow always has it!

very cool

Very cool! I'm fascinated, why does it work? Is it due to how credit card companies assign card numbers? How would a couple of math operations check the validity of a credit card number?

It is used to distinguish valid numbers from mistyped or rather wrong numbers. The

check digitis appended to the partial number to generate valid number.