# National Provider Identifier (NPI) and its checksum

Healthcare providers in the United States are required to have an ID number known as the NPI (National Provider Identifier). This is a 10-digit unique identifier which serves as the primary key in a publicly available database. You can use the NPI number to look up a provider’s name, credentials, their practice location, etc. The use of NPI numbers was required by HIPAA.

The specification for the NPI number format says that the first digit must be either 1 or 2. Currently every NPI in the database starts with 1. There are about 8.4 million NPIs currently, so it’ll be a while before they’ll need to roll the first digit over to 2.

The last digit of the NPI is a check sum. The check sum uses the Luhn algorithm, the same check sum used for credit cards and other kinds of identifiers. The Luhn algorithm was developed in 1954 and was designed to be easy to implement by hand. It’s kind of a quirky algorithm, but it will catch all single-digit errors and nearly all transposition errors.

The Luhn algorithm is not applied to the NPI itself but by first prepending 80840 to the (first nine digits of) the NPI.

For example, let’s look at 1993999998. This is not (currently) anyone’s NPI, but it has a valid NPI format because the Luhn checksum of 80840199399999 is 8. We will verify this with the code below.

## Python code for Luhn checksum

The following code computes the Luhn checksum.

```    def checksum(payload):
digits = [int(c) for c in reversed(str(payload))]
s = 0
for i, d in enumerate(digits):
if i % 2 == 0:
t = 2*d
if t > 9:
t -= 9
s += t
else:
s += d
return (s*9) % 10
```

And the following checks whether the last digit of a number is the checksum of the previous digits.

```    def verify(fullnumber):
return checksum(payload) == fullnumber % 10
```

And finally, the following validates an NPI number.

```    def verify_npi(npi):
return verify(int("80840" + str(npi)))
```

Here we apply the code above to the hypothetical NPI number mentioned above.

```    assert(checksum(80840199399999) == 8)
assert(verify(808401993999998))
assert(verify_npi(1993999998))
```