1 /* $NetBSD: mersenne.c,v 1.1.1.2 2014/04/24 12:45:39 pettai Exp $ */
3 /* Finds Mersenne primes using the Lucas-Lehmer test
5 * Tom St Denis, tomstdenis@gmail.com
11 is_mersenne (long s
, int *pp
)
18 if ((res
= mp_init (&n
)) != MP_OKAY
) {
22 if ((res
= mp_init (&u
)) != MP_OKAY
) {
27 if ((res
= mp_2expt(&n
, s
)) != MP_OKAY
) {
30 if ((res
= mp_sub_d (&n
, 1, &n
)) != MP_OKAY
) {
37 /* for k=1 to s-2 do */
38 for (k
= 1; k
<= s
- 2; k
++) {
39 /* u = u^2 - 2 mod n */
40 if ((res
= mp_sqr (&u
, &u
)) != MP_OKAY
) {
43 if ((res
= mp_sub_d (&u
, 2, &u
)) != MP_OKAY
) {
47 /* make sure u is positive */
48 while (u
.sign
== MP_NEG
) {
49 if ((res
= mp_add (&u
, &n
, &u
)) != MP_OKAY
) {
55 if ((res
= mp_reduce_2k (&u
, &n
, 1)) != MP_OKAY
) {
60 /* if u == 0 then its prime */
61 if (mp_iszero (&u
) == 1) {
62 mp_prime_is_prime(&n
, 8, pp
);
63 if (*pp
!= 1) printf("FAILURE\n");
72 /* square root of a long < 65536 */
81 x2
= x1
- ((x1
* x1
) - x
) / (2 * x1
);
91 /* is the long prime by brute force */
98 for (z
= 2; z
<= y
; z
++) {
119 /* test if 2^k - 1 is prime */
120 if (is_mersenne (k
, &pp
) != MP_OKAY
) {
121 printf ("Whoa error\n");
129 /* display if prime */
130 printf ("2^%-5ld - 1 is prime, test took %ld ticks\n", k
, tt
);
133 /* goto next odd exponent */
136 /* but make sure its prime */
137 while (isprime (k
) == 0) {
144 /* Source: /cvs/libtom/libtommath/etc/mersenne.c,v */
146 /* Date: 2006/03/31 14:18:47 */