• Source
    1. #include <stdio.h>
    2. #include <math.h>
    3. #include <stdlib.h>
    4.  
    5. int cuentaBits(int numero) {
    6. int bits_necesarios = 0;
    7. while(numero > 0) {
    8. bits_necesarios++;
    9. numero = numero >> 1 ; // Desplazo bits (división por 2)
    10. }
    11. return bits_necesarios;
    12. }
    13. int* binario( int n , int array [],int size){
    14.  
    15. for (int i = size-1; i > -1 ; i--){
    16. array[i] = n%2;
    17. n = n / 2;
    18. }
    19. return array;
    20. }
    21.  
    22.  
    23. int expModular(int b, int n,int m){
    24. //Funcion para el calculo de la exponenciacion modular
    25. // Se obtiene (b^n)%m muy funcional si son enteros grandes
    26. int k = cuentaBits(n);
    27. int temp[k];
    28.  
    29. int* rep = binario(n,temp,k);
    30.  
    31. int x = 1;
    32. int potencia = b % m;
    33. for(int i = k-1; i > -1; i--){
    34. if (rep[i]){
    35. x = (x * potencia) % m;
    36. }
    37. potencia = (potencia * potencia) % m;
    38. }
    39. return x;
    40. }
    41.  
    42. int millerTest(int d, int n){
    43. /*---------------Falta entender----------*/
    44. // Numero aleatorio entre [2..n-2]
    45.  
    46. // Corner cases make sure that n > 4
    47. int a = 2 + rand() % (n - 4);
    48.  
    49. // Calcular a^d % n
    50. int x = expModular(a,d,n);
    51.  
    52. if (x == 1 || x == n-1)
    53. return 1;
    54.  
    55. // Keep squaring x while one of the following doesn't
    56. // happen
    57. // (i) d does not reach n-1
    58. // (ii) (x^2) % n is not 1
    59. // (iii) (x^2) % n is not n-1
    60. while (d != n-1)
    61. {
    62. x = (x * x) % n;
    63. d = d * 2;
    64.  
    65. if (x == 1) return 0;
    66. if (x == n-1) return 1;
    67. }
    68.  
    69. return 0; /*Compuesto*/
    70. }
    71. int isPrime(int n, int iterations){
    72.  
    73. /*Casos < 3*/
    74. if(n == 2 || n == 3){
    75. return 1;
    76. }
    77. if(n < 4 || n%2 == 0){ /*Revisar pares y negativos y 1 */
    78. return 0;
    79. }
    80. int d = n - 1;
    81. while(d%2 == 0){ /*Mientras es par*/
    82. d = d/2;
    83. }
    84.  
    85. for (int i = 0; i < iterations; i++){
    86. if (!millerTest(d, n)) {
    87. return 0;
    88. }
    89. }
    90. return 1;
    91. }
    92.  
    93. int main(void) {
    94. int i = 0;
    95. int n = 0;
    96.  
    97. int k = 100; /*Nivel de precicion*/
    98.  
    99. for (int n = 1; n < 100; n++) {
    100. if (isPrime(n, k)) {
    101. printf(" %i ", n);
    102. }
    103. }
    104. return 0;
    105.  
    106. }
    107.