In Brazil, each individual has a unique and definitive CPF (Cadastro de Pessoas Físicas) registration number, which identifies him or her to the Internal Revenue Service. This registration number is made up of 9 digits, grouped 3 by 3. For example, 313.402.809-30.
The CPF is validated through the verifying digits, which are the last 2 digits of the CPF, i.e. from the last 2 digits of the CPF you know if the previous 9 digits are valid.
CPF Generation Algorithm:
- Calculation of the first check digit:
Let’s take a vector [latex] a E R^9 [/latex] whose components are the digits that make up the CPF number in the order given. For the CPF cited as an example at the beginning of this article, 313.402.809-30, we have the vector:
[latex] a = (3, 1, 3, 4, 0, 2, 8, 0, 9) [/latex]
We determine the scalar product of this vector with the (standard) vector
[latex] b = (10, 9, 8, 7, 6, 5, 4, 3, 2) [/latex]
that is,
[latex] a . b = (3, 1, 3, 4, 0, 2, 8, 0, 9) . (10, 9, 8, 7, 6, 5, 4, 3, 2) = 30 + 9 + 24 + 28 + 0 + 10 + 32 + 0 + 18 = 151 [/latex]
Next, we take the remainder of the integer division of this scalar product by 11. If the remainder of this integer division is 0 or 1, then the first check digit is 0. Otherwise (remainder between 2 and 10), the first check digit is given as 11 – remainder.
For the example in question, dividing 151 by 11 results in a quotient of 13 and a remainder of 8. So the first check digit is [latex] 11 – 8 = 3 . [/latex]
- Calculation of the second check digit:
Let’s take a vector [latex] c E R^10 [/latex] whose first nine components are the digits that make up the CPF number in the order given, and the last component is the first check digit found. For the example in question we have:
[latex] c = (3, 1, 3, 4, 0, 2, 8, 0, 9, 3) [/latex]
We determine the scalar product of this vector with the (standard) vector
[latex] d = (11, 10, 9, 8, 7, 6, 5, 4, 3, 2) , [/latex]
that is,
[latex] c . d = (3, 1, 3, 4, 0, 2, 8, 0, 9, 3) . (11, 10, 9, 8, 7, 6, 5, 4, 3, 2) = 33 + 10 + 27 + 32 + 0 + 12 + 40 + 0 + 27 + 6 = 187 [/latex]
Next, we take the remainder of the integer division of this scalar product by 11. If the remainder of this integer division is 0 or 1, then the second check digit is 0. Otherwise (remainder between 2 and 10), the second check digit is given by 11 – remainder.
For the example in question, dividing 187 by 11 results in a quotient of 17 and a remainder of 0. Therefore, the second check digit is 0.
Bibliography: Analytical Geometry – Fabiano José dos Santos and Silvimar Fábio Ferreira.