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.]
6 // We work with integers.
7 #include <cl_integer.h>
9 // Checks whether 2^q-1 is prime, q an odd prime.
10 bool mersenne_prime_p (int q)
12 cl_I m = ((cl_I)1 << q) - 1;
15 for (i = 0, L_i = 4; i < q-2; i++)
16 L_i = mod(L_i*L_i - 2, m);
20 // Same thing, but optimized.
21 bool mersenne_prime_p_opt (int q)
23 cl_I m = ((cl_I)1 << q) - 1;
26 for (i = 0, L_i = 4; i < q-2; i++) {
27 L_i = square(L_i) - 2;
28 L_i = ldb(L_i,cl_byte(q,q)) + ldb(L_i,cl_byte(q,0));
35 // Now we work with modular integers.
36 #include <cl_modinteger.h>
38 // Same thing, but using modular integers.
39 bool mersenne_prime_p_modint (int q)
41 cl_I m = ((cl_I)1 << q) - 1;
42 cl_modint_ring R = cl_find_modint_ring(m); // Z/mZ
45 for (i = 0, L_i = R->canonhom(4); i < q-2; i++)
46 L_i = R->minus(R->square(L_i),R->canonhom(2));
47 return R->equal(L_i,R->zero());
50 #include <cl_io.h> // we do I/O
51 #include <stdlib.h> // declares exit()
52 #include <cl_timing.h>
54 int main (int argc, char* argv[])
57 fprint(cl_stderr, "Usage: lucaslehmer exponent\n");
60 int q = atoi(argv[1]);
61 if (!(q >= 2 && ((q % 2)==1))) {
62 fprint(cl_stderr, "Usage: lucaslehmer q with q odd prime\n");
66 { CL_TIMING; isprime = mersenne_prime_p(q); }
67 { CL_TIMING; isprime = mersenne_prime_p_opt(q); }
68 { CL_TIMING; isprime = mersenne_prime_p_modint(q); }
69 fprint(cl_stdout, "2^");
70 fprintdecimal(cl_stdout, q);
71 fprint(cl_stdout, "-1 is ");
73 fprint(cl_stdout, "prime");
75 fprint(cl_stdout, "composite");
76 fprint(cl_stdout, "\n");
79 // Computing time on a i486, 33 MHz: