1 /* Finds Mersenne primes using the Lucas-Lehmer test
3 * Tom St Denis, tomstdenis@iahu.ca
9 is_mersenne (long s, int *pp)
16 if ((res = mp_init (&n)) != MP_OKAY) {
20 if ((res = mp_init (&u)) != MP_OKAY) {
25 if ((res = mp_2expt(&n, s)) != MP_OKAY) {
28 if ((res = mp_sub_d (&n, 1, &n)) != MP_OKAY) {
35 /* for k=1 to s-2 do */
36 for (k = 1; k <= s - 2; k++) {
37 /* u = u^2 - 2 mod n */
38 if ((res = mp_sqr (&u, &u)) != MP_OKAY) {
41 if ((res = mp_sub_d (&u, 2, &u)) != MP_OKAY) {
45 /* make sure u is positive */
46 while (u.sign == MP_NEG) {
47 if ((res = mp_add (&u, &n, &u)) != MP_OKAY) {
53 if ((res = mp_reduce_2k (&u, &n, 1)) != MP_OKAY) {
58 /* if u == 0 then its prime */
59 if (mp_iszero (&u) == 1) {
60 mp_prime_is_prime(&n, 8, pp);
61 if (*pp != 1) printf("FAILURE\n");
70 /* square root of a long < 65536 */
79 x2 = x1 - ((x1 * x1) - x) / (2 * x1);
89 /* is the long prime by brute force */
96 for (z = 2; z <= y; z++) {
117 /* test if 2^k - 1 is prime */
118 if (is_mersenne (k, &pp) != MP_OKAY) {
119 printf ("Whoa error\n");
127 /* display if prime */
128 printf ("2^%-5ld - 1 is prime, test took %ld ticks\n", k, tt);
131 /* goto next odd exponent */
134 /* but make sure its prime */
135 while (isprime (k) == 0) {