1 /*
2     Copyright (C) 2012 William Hart
3     Copyright (C) 2020 Fredrik Johansson
4 
5     This file is part of FLINT.
6 
7     FLINT is free software: you can redistribute it and/or modify it under
8     the terms of the GNU Lesser General Public License (LGPL) as published
9     by the Free Software Foundation; either version 2.1 of the License, or
10     (at your option) any later version.  See <http://www.gnu.org/licenses/>.
11 */
12 
13 #include <gmp.h>
14 #include "flint.h"
15 #include "ulong_extras.h"
16 #include "fmpz.h"
17 #include "mpn_extras.h"
18 
19 int
fmpz_is_probabprime(const fmpz_t n)20 fmpz_is_probabprime(const fmpz_t n)
21 {
22     if (!COEFF_IS_MPZ(*n))
23     {
24         slong v = *n;
25 
26         if (v <= 1)
27             return 0;
28         return n_is_probabprime(v);
29     }
30     else
31     {
32         __mpz_struct * z;
33         mp_ptr d;
34         slong size, bits, trial_primes;
35 
36         z = COEFF_TO_PTR(*n);
37         size = z->_mp_size;
38         d = z->_mp_d;
39 
40         if (size < 0)
41             return 0;
42         if (size == 1)
43             return n_is_probabprime(d[0]);
44 
45         if (d[0] % 2 == 0)
46             return 0;
47 
48         bits = size * FLINT_BITS + FLINT_BIT_COUNT(d[size-1]);
49         trial_primes = bits;
50 
51         if (flint_mpn_factor_trial(d, size, 1, trial_primes))
52             return 0;
53 
54         if (fmpz_is_square(n))
55             return 0;
56 
57         return fmpz_is_probabprime_BPSW(n);
58     }
59 }
60