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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
Copyright (C) 2009 William Hart
Copyright (C) 2014 Abhinav Baid
Copyright (C) 2021 Abhinav Baid
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 "fmpz.h"
/* r = a mod m with various options for the range of r */
void _fmpz_smod(
fmpz_t r,
const fmpz_t a,
const fmpz_t m,
int sign, /* -1: |r| < |m| & sgn(r) = sgn(a) or r == 0
0: |r| < |m| & sgn(r) = sgn(m) or r == 0
1: -|m| < 2r <= |m| */
fmpz_t t) /* temp not aliased with anything else */
{
if (sign < 0)
{
if (fmpz_cmpabs(m, a) > 0)
fmpz_set(r, a);
else
fmpz_tdiv_qr(t, r, a, m);
}
else if (sign > 0)
{
int cmp = fmpz_cmp2abs(m, a);
if (cmp >= 0)
{
if (cmp == 0)
fmpz_abs(r, a);
else
fmpz_set(r, a);
}
else if (m != r)
{
fmpz_fdiv_qr(t, r, a, m); /* r is zero or has same sign as m */
cmp = fmpz_cmp2abs(m, r);
if (cmp == 0)
fmpz_abs(r, r);
else if (cmp < 0)
fmpz_sub(r, r, m);
}
else
{
fmpz_set(t, m);
fmpz_fdiv_r(r, a, t);
cmp = fmpz_cmp2abs(t, r);
if (cmp == 0)
fmpz_abs(r, r);
else if (cmp < 0)
fmpz_sub(r, r, t);
}
}
else
{
fmpz_fdiv_qr(t, r, a, m);
}
}
void fmpz_smod(fmpz_t f, const fmpz_t g, const fmpz_t h)
{
fmpz c2 = *h;
if (!COEFF_IS_MPZ(c2)) /* h is small */
{
ulong tmp;
tmp = FLINT_ABS(c2);
fmpz_mod(f, g, h);
if (fmpz_cmp_ui(f, tmp / 2) > 0)
{
fmpz_sub_ui(f, f, tmp);
}
}
else /* h is large */
{
fmpz_t tmp;
fmpz_init(tmp);
_fmpz_smod(f, g, h, 1, tmp);
fmpz_clear(tmp);
}
}