2022-11-23 22:14:41 +08:00
# Instructions
2025-07-15 07:50:26 -04:00
Determine whether a number is valid according to the [Luhn formula][luhn].
2022-11-23 22:14:41 +08:00
2025-07-15 07:50:26 -04:00
The number will be provided as a string.
2022-11-23 22:14:41 +08:00
2025-07-15 07:50:26 -04:00
## Validating a number
2022-11-23 22:14:41 +08:00
2023-08-29 05:42:16 -07:00
Strings of length 1 or less are not valid.
Spaces are allowed in the input, but they should be stripped before checking.
All other non-digit characters are disallowed.
2022-11-23 22:14:41 +08:00
2025-07-15 07:50:26 -04:00
## Examples
2022-11-23 22:14:41 +08:00
2025-07-15 07:50:26 -04:00
### Valid credit card number
2022-11-23 22:14:41 +08:00
2025-07-15 07:50:26 -04:00
The number to be checked is `4539 3195 0343 6467` .
The first step of the Luhn algorithm is to start at the end of the number and double every second digit, beginning with the second digit from the right and moving left.
2022-11-23 22:14:41 +08:00
```text
2024-12-06 04:18:51 -08:00
4539 3195 0343 6467
↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ (double these)
2022-11-23 22:14:41 +08:00
```
2025-07-15 07:50:26 -04:00
If the result of doubling a digit is greater than 9, we subtract 9 from that result.
We end up with:
2022-11-23 22:14:41 +08:00
```text
8569 6195 0383 3437
```
2025-07-15 07:50:26 -04:00
Finally, we sum all digits.
If the sum is evenly divisible by 10, the original number is valid.
2022-11-23 22:14:41 +08:00
```text
2025-07-15 07:50:26 -04:00
8 + 5 + 6 + 9 + 6 + 1 + 9 + 5 + 0 + 3 + 8 + 3 + 3 + 4 + 3 + 7 = 80
2022-11-23 22:14:41 +08:00
```
2025-07-15 07:50:26 -04:00
80 is evenly divisible by 10, so number `4539 3195 0343 6467` is valid!
### Invalid Canadian SIN
The number to be checked is `066 123 478` .
2022-11-23 22:14:41 +08:00
2025-07-15 07:50:26 -04:00
We start at the end of the number and double every second digit, beginning with the second digit from the right and moving left.
2022-11-23 22:14:41 +08:00
```text
2025-07-15 07:50:26 -04:00
066 123 478
↑ ↑ ↑ ↑ (double these)
2022-11-23 22:14:41 +08:00
```
2025-07-15 07:50:26 -04:00
If the result of doubling a digit is greater than 9, we subtract 9 from that result.
We end up with:
2022-11-23 22:14:41 +08:00
```text
2025-07-15 07:50:26 -04:00
036 226 458
2022-11-23 22:14:41 +08:00
```
2025-07-15 07:50:26 -04:00
We sum the digits:
2022-11-23 22:14:41 +08:00
```text
2025-07-15 07:50:26 -04:00
0 + 3 + 6 + 2 + 2 + 6 + 4 + 5 + 8 = 36
2022-11-23 22:14:41 +08:00
```
2025-07-15 07:50:26 -04:00
36 is not evenly divisible by 10, so number `066 123 478` is not valid!
2023-08-29 05:42:16 -07:00
[luhn]: https://en.wikipedia.org/wiki/Luhn_algorithm