You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.9 KiB

25 years ago
  1. // Check whether a mersenne number is prime,
  2. // using the Lucas-Lehmer test.
  3. // [Donald Ervin Knuth: The Art of Computer Programming, Vol. II:
  4. // Seminumerical Algorithms, second edition. Section 4.5.4, p. 391.]
  5. // We work with integers.
  6. #include <cl_integer.h>
  7. // Checks whether 2^q-1 is prime, q an odd prime.
  8. bool mersenne_prime_p (int q)
  9. {
  10. cl_I m = ((cl_I)1 << q) - 1;
  11. int i;
  12. cl_I L_i;
  13. for (i = 0, L_i = 4; i < q-2; i++)
  14. L_i = mod(L_i*L_i - 2, m);
  15. return (L_i==0);
  16. }
  17. // Same thing, but optimized.
  18. bool mersenne_prime_p_opt (int q)
  19. {
  20. cl_I m = ((cl_I)1 << q) - 1;
  21. int i;
  22. cl_I L_i;
  23. for (i = 0, L_i = 4; i < q-2; i++) {
  24. L_i = square(L_i) - 2;
  25. L_i = ldb(L_i,cl_byte(q,q)) + ldb(L_i,cl_byte(q,0));
  26. if (L_i >= m)
  27. L_i = L_i - m;
  28. }
  29. return (L_i==0);
  30. }
  31. // Now we work with modular integers.
  32. #include <cl_modinteger.h>
  33. // Same thing, but using modular integers.
  34. bool mersenne_prime_p_modint (int q)
  35. {
  36. cl_I m = ((cl_I)1 << q) - 1;
  37. cl_modint_ring R = cl_find_modint_ring(m); // Z/mZ
  38. int i;
  39. cl_MI L_i;
  40. for (i = 0, L_i = R->canonhom(4); i < q-2; i++)
  41. L_i = R->minus(R->square(L_i),R->canonhom(2));
  42. return R->equal(L_i,R->zero());
  43. }
  44. #include <cl_io.h> // we do I/O
  45. #include <stdlib.h> // declares exit()
  46. #include <cl_timing.h>
  47. int main (int argc, char* argv[])
  48. {
  49. if (!(argc == 2)) {
  50. fprint(cl_stderr, "Usage: lucaslehmer exponent\n");
  51. exit(1);
  52. }
  53. int q = atoi(argv[1]);
  54. if (!(q >= 2 && ((q % 2)==1))) {
  55. fprint(cl_stderr, "Usage: lucaslehmer q with q odd prime\n");
  56. exit(1);
  57. }
  58. bool isprime;
  59. { CL_TIMING; isprime = mersenne_prime_p(q); }
  60. { CL_TIMING; isprime = mersenne_prime_p_opt(q); }
  61. { CL_TIMING; isprime = mersenne_prime_p_modint(q); }
  62. fprint(cl_stdout, "2^");
  63. fprintdecimal(cl_stdout, q);
  64. fprint(cl_stdout, "-1 is ");
  65. if (isprime)
  66. fprint(cl_stdout, "prime");
  67. else
  68. fprint(cl_stdout, "composite");
  69. fprint(cl_stdout, "\n");
  70. }
  71. // Computing time on a i486, 33 MHz:
  72. // 1279: 2.02 s
  73. // 2281: 8.74 s
  74. // 44497: 14957 s