fork download
  1. using static System.Console;
  2. using System;
  3. using System.Linq;
  4.  
  5. public class Test {
  6. public static void Main() {
  7. WriteLine(GerarCpf(Uf.SP));
  8. WriteLine(GerarCpf());
  9. }
  10. public static string GerarCpf(Uf uf = Uf.NA) {
  11. var random = new Random();
  12. int[] digitos = new int[11];
  13. int soma = 0, soma2 = 0;
  14. do {
  15. for (var i = 0; i < 8; i++) {
  16. digitos[i] = random.Next(10);
  17. soma += digitos[i] * (10 - i);
  18. soma2 += digitos[i] * (11 - i);
  19. }
  20. digitos[8] = uf == Uf.NA ? random.Next(10) : (int)uf;
  21. soma += digitos[8] * 2;
  22. soma2 += digitos[8] * 3;
  23. } while (Repetidos(digitos));
  24. var resto = soma % 11;
  25. digitos[9] = resto < 2 ? 0 : 11 - resto;
  26. soma2 += digitos[9] * 2;
  27. resto = soma2 % 11;
  28. digitos[10] = resto < 2 ? 0 : 11 - resto;
  29. return string.Join("", digitos.Select(p => p.ToString()).ToArray());
  30. }
  31.  
  32. private static bool Repetidos(int[] digitos) {
  33. var val = digitos[0];
  34. return digitos.Take(9).All(x => x == val);
  35. }
  36. }
  37.  
  38. public enum Uf {
  39. AC = 2, AL = 4, AP = 2, AM = 2, BA = 5, CE = 3, DF = 1, ES = 7, GO = 1, MA = 3, MT = 1, MS = 1, MG = 6, PA = 2, PB = 4, PR = 9, PE = 4, PI = 3, RJ = 7, RN = 4, RS = 0, RO = 2, RR = 2, SC = 9, SP = 8, SE = 5, TO = 1, NA = -1
  40. }
  41.  
  42. //https://pt.stackoverflow.com/q/33669/101
Success #stdin #stdout 0.03s 23796KB
stdin
Standard input is empty
stdout
59501626849
84965166795