aboutsummaryrefslogtreecommitdiffstats
path: root/src/zmodpow.c
blob: 42bed2ff5b49c063ab6c0cd60491b10825678fec (plain) (blame)
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
/* See LICENSE file for copyright and license details. */
#include "internals"

#include <errno.h>

#define tb  libzahl_tmp_pow_b
#define tc  libzahl_tmp_pow_c
#define td  libzahl_tmp_pow_d


void
zmodpow(z_t a, z_t b, z_t c, z_t d)
{
	size_t i, n;

	if (zsignum(c) <= 0) {
		if (zzero(c)) {
			if (zzero(b)) {
				errno = EDOM; /* Indeterminate form: 0:th power of 0 */
				FAILURE_JUMP();
			}
			zsetu(a, 1);
		} else if (zzero(b) || zzero(d)) {
			errno = EDOM; /* Undefined form: Division by 0 */
			FAILURE_JUMP();
		} else {
			SET_SIGNUM(a, 0);
		}
		return;
	} else if (zzero(d)) {
		errno = EDOM; /* Undefined form: Division by 0 */
		FAILURE_JUMP();
	} else if (zzero(b)) {
		SET_SIGNUM(a, 0);
		return;
	}

	n = zbits(c);

	zmod(tb, b, d);
	zset(tc, c);
	zset(td, d);
	zsetu(a, 1);

	for (i = 0; i < n; i++) {
		if (zbtest(tc, i))
			zmodmul(a, a, tb, td);
		zmodsqr(tb, tb, td);
	}
}