aboutsummaryrefslogtreecommitdiffstats
path: root/src/zsub.c
diff options
context:
space:
mode:
authorMattias Andrée <maandree@kth.se>2016-03-03 10:33:29 +0100
committerMattias Andrée <maandree@kth.se>2016-03-03 10:35:22 +0100
commitc0bc7b6e2d090554c9d940bc3614e089a688503a (patch)
treea1b85a760ec1e18bdd0ceac15b802bdf6409e625 /src/zsub.c
parentznot man page: notes on representation and tendness toward zero (diff)
downloadlibzahl-c0bc7b6e2d090554c9d940bc3614e089a688503a.tar.gz
libzahl-c0bc7b6e2d090554c9d940bc3614e089a688503a.tar.bz2
libzahl-c0bc7b6e2d090554c9d940bc3614e089a688503a.tar.xz
Add zabs, zadd, zdiv, zmod, zmodmul, zmodpow, zneg, zpow, zsub, and the newly introduced zmodsqr
Signed-off-by: Mattias Andrée <maandree@kth.se>
Diffstat (limited to 'src/zsub.c')
-rw-r--r--src/zsub.c70
1 files changed, 70 insertions, 0 deletions
diff --git a/src/zsub.c b/src/zsub.c
new file mode 100644
index 0000000..437e329
--- /dev/null
+++ b/src/zsub.c
@@ -0,0 +1,70 @@
+/* See LICENSE file for copyright and license details. */
+#include "internals"
+
+#include <stdlib.h>
+#include <string.h>
+
+
+void
+zsub_unsigned(z_t a, z_t b, z_t c)
+{
+ int magcmp = zcmpmag(b, c);
+ z_t s;
+ size_t i, n;
+ zahl_char_t carry[] = {0, 0};
+
+ if (magcmp <= 0) {
+ if (magcmp == 0) {
+ SET_SIGNUM(a, 0);
+ return;
+ }
+ if (a != c)
+ zset(a, c);
+ *subtrahend = *b;
+ } else {
+ if (a != b)
+ zset(a, b);
+ *subtrahend = *c;
+ }
+
+ n = a->used < s->used ? a->used : s->used;
+
+ for (i = 0; i < n; i++) {
+ carry[~i & 1] = carry[i & 1] ? (a->chars[i] <= s->chars[i]) : (a->chars[i] < s->chars[i]);
+ a->chars[i] -= s->chars[i];
+ a->chars[i] -= carry[i & 1];
+ }
+
+ if (carry[i] & 1) {
+ while (!a->chars[i])
+ a->chars[i++] = ZAHL_CHAR_MAX;
+ a->chars[i] -= 1;
+ }
+ SET_SIGNUM(a, magcmp);
+}
+
+void
+zsub(z_t a, z_t b, z_t c)
+{
+ if (b == c) {
+ SET_SIGNUM(a, 0);
+ } else if (zzero(b)) {
+ zneg(a, c);
+ } else if (zzero(c)) {
+ if (a != b)
+ zset(a, b);
+ } else if ((zsignum(b) | zsignum(c)) < 0) {
+ if (zsignum(b) < 0) {
+ if (zsignum(c) < 0) {
+ zsub_unsigned(a, c, b);
+ } else {
+ zadd_unsigned(a, b, c);
+ SET_SIGNUM(a, -zsignum(a));
+ }
+ } else {
+ zadd_unsigned(a, b, c);
+ }
+ } else {
+ zsub_unsigned(a, b, c);
+ }
+}