1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
Authored 2015 by Daniel S. Roche; US Government work in the public domain.
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/
#include "gmpcompat.h"
#include "fmpz.h"
#include "ulong_extras.h"
void fmpz_nextprime(fmpz_t res, const fmpz_t n, int proved)
{
if (fmpz_sgn(n) <= 0)
{
fmpz_set_ui(res, UWORD(2));
return;
}
else if (COEFF_IS_MPZ(*n))
{
/* n is big */
mpz_ptr res_mpz = _fmpz_promote(res);
mpz_nextprime(res_mpz, COEFF_TO_PTR(*n));
}
else if (FLINT_BIT_COUNT(*n) < SMALL_FMPZ_BITCOUNT_MAX)
{
/* n and res will both be small */
_fmpz_demote(res);
*res = n_nextprime(*n, proved);
return;
}
else if (res != n)
{
/* n is small, but res might not be */
mpz_t temp_n;
mpz_ptr res_mpz = _fmpz_promote(res);
flint_mpz_init_set_ui(temp_n, *n);
mpz_nextprime(res_mpz, temp_n);
_fmpz_demote_val(res);
mpz_clear(temp_n);
}
else
{
/* same as above case, but need to handle aliasing here. */
mpz_ptr res_mpz = _fmpz_promote_val(res);
mpz_nextprime(res_mpz, res_mpz);
_fmpz_demote_val(res);
}
if (proved)
{
if (!fmpz_is_prime(res))
{
/* Keep searching. No big penalty for recursion here because this
* will almost never happen.
*/
fmpz_nextprime(res, res, proved);
}
}
}