1 /* TomsFastMath, a fast ISO C bignum library.
3 * This project is meant to fill in where LibTomMath
4 * falls short. That is speed ;-)
6 * This project is public domain and free for all purposes.
8 * Tom St Denis, tomstdenis@gmail.com
10 #include <tfm_private.h>
12 /* Miller-Rabin test of "a" to the base of "b" as described in
13 * HAC pp. 139 Algorithm 4.24
15 * Sets result to 0 if definitely composite or 1 if probably prime.
16 * Randomly the chance of error is no more than 1/4 and often
19 void fp_prime_miller_rabin (fp_int * a, fp_int * b, int *result)
28 if (fp_cmp_d(b, 1) != FP_GT) {
34 fp_sub_d(&n1, 1, &n1);
36 /* set 2**s * r = n1 */
37 fp_init_copy(&r, &n1);
39 /* count the number of least significant bits
44 /* now divide n - 1 by 2**s */
45 fp_div_2d (&r, s, &r, NULL);
47 /* compute y = b**r mod a */
49 fp_exptmod(b, &r, a, &y);
51 /* if y != 1 and y != n1 do */
52 if (fp_cmp_d (&y, 1) != FP_EQ && fp_cmp (&y, &n1) != FP_EQ) {
54 /* while j <= s-1 and y != n1 */
55 while ((j <= (s - 1)) && fp_cmp (&y, &n1) != FP_EQ) {
56 fp_sqrmod (&y, a, &y);
58 /* if y == 1 then composite */
59 if (fp_cmp_d (&y, 1) == FP_EQ) {
65 /* if y != n1 then composite */
66 if (fp_cmp (&y, &n1) != FP_EQ) {
71 /* probably prime now */