probably_prime.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "os.h"
  2. #include <mp.h>
  3. #include <libsec.h>
  4. // Miller-Rabin probabilistic primality testing
  5. // Knuth (1981) Seminumerical Algorithms, p.379
  6. // Menezes et al () Handbook, p.39
  7. // 0 if composite; 1 if almost surely prime, Pr(err)<1/4**nrep
  8. int
  9. probably_prime(mpint *n, int nrep)
  10. {
  11. int j, k, rep, nbits, isprime = 1;
  12. mpint *nm1, *q, *x, *y, *r;
  13. if(n->sign < 0)
  14. sysfatal("negative prime candidate");
  15. if(nrep <= 0)
  16. nrep = 18;
  17. k = mptoi(n);
  18. if(k == 2) // 2 is prime
  19. return 1;
  20. if(k < 2) // 1 is not prime
  21. return 0;
  22. if((n->p[0] & 1) == 0) // even is not prime
  23. return 0;
  24. // test against small prime numbers
  25. if(smallprimetest(n) < 0)
  26. return 0;
  27. // fermat test, 2^n mod n == 2 if p is prime
  28. x = uitomp(2, nil);
  29. y = mpnew(0);
  30. mpexp(x, n, n, y);
  31. k = mptoi(y);
  32. if(k != 2){
  33. mpfree(x);
  34. mpfree(y);
  35. return 0;
  36. }
  37. nbits = mpsignif(n);
  38. nm1 = mpnew(nbits);
  39. mpsub(n, mpone, nm1); // nm1 = n - 1 */
  40. k = mplowbits0(nm1);
  41. q = mpnew(0);
  42. mpright(nm1, k, q); // q = (n-1)/2**k
  43. for(rep = 0; rep < nrep; rep++){
  44. // x = random in [2, n-2]
  45. r = mprand(nbits, prng, nil);
  46. mpmod(r, nm1, x);
  47. mpfree(r);
  48. if(mpcmp(x, mpone) <= 0)
  49. continue;
  50. // y = x**q mod n
  51. mpexp(x, q, n, y);
  52. if(mpcmp(y, mpone) == 0 || mpcmp(y, nm1) == 0)
  53. goto done;
  54. for(j = 1; j < k; j++){
  55. mpmul(y, y, x);
  56. mpmod(x, n, y); // y = y*y mod n
  57. if(mpcmp(y, nm1) == 0)
  58. goto done;
  59. if(mpcmp(y, mpone) == 0){
  60. isprime = 0;
  61. goto done;
  62. }
  63. }
  64. isprime = 0;
  65. }
  66. done:
  67. mpfree(y);
  68. mpfree(x);
  69. mpfree(q);
  70. mpfree(nm1);
  71. return isprime;
  72. }