The Math behind a Brazilian CPF.

luannzin
2 min readMar 4, 2024

--

Mathematics is present in various natural aspects of our daily lives.

Today I’m going to explain how the generation and validation of a CPF (Brazilian Individual Taxpayer Registry) work.

Formula

The first eight digits are the base numbers of the CPF, which are defined by the Federal Revenue Service.

The ninth digit defines the Fiscal Region responsible for the registration.

The penultimate digit is the verifier digit for the first nine digits.

The last digit is the verifier digit for the preceding nine digits.

Simplifying

The first 8 numbers can be random (123.456.78x-xx or 000.000.00x-xx), what really matters are the next 3.

Ninth Digit

1 — DF, GO, MS, MT, and TO 2 — AC, AM, AP, PA, RO, and RR 3 — CE, MA, and PI 4 — AL, PB, PE, RN 5 — BA and SE 6 — MG 7 — ES and RJ 8 — SP 9 — PR and SC 0 — RS

According to this table, your ninth digit indicates which Fiscal Region is responsible for it. (Test it with your CPF. 😉)

Tenth Digit

This is our first verifier, and it uses the following formula:

The first nine numbers are sequentially multiplied by the sequence 10, 9, 8, 7, 6, 5, 4, 3, 2 (the first by 10, the second by 9, and so on).

Then, you add up the results and calculate the remainder of dividing this sum by 11.

Example:

Suppose the total sum was 162.

162 % 11 = 8

The remainder of the division.

If this remainder is 0 or 1, then the digit should be 0.

Otherwise, the digit is (11 — remainder).

Example:

11–8 = 3

Our tenth digit would be 3.

Eleventh Digit

For this digit, the formula works the same way, but it uses the 9 numbers before it.

That is, now our first verifier digit also comes into this count.

And with that, even with just a pen and a piece of paper, you can already manually generate valid CPFs.

Automation

And to test this logic and the formulas, I made an extremely simple CPF generator.

👉 https://cpf.social/ 👈

Here’s the repository:

👉 https://github.com/luannzin/cpf-social 👈

And here’s the generation algorithm:

👉 https://github.com/luannzin/cpf-social/blob/main/app/helpers/generateCpf.ts 👈

The project is an MVP and Open Source, so any ideas are extremely welcome.

I’ll make a post about the Luhn Algorithm, so stay tuned. 👑

Follow my Github for the next projects.

👉 https://github.com/luannzin 👈

--

--