commit 4e5eeccd8049accf5604efad12cd2a9f11a1df2d
parent 1c5d537e98f90c9b479d772c65c39bcbebe14685
Author: olikru <olikru@tkruger.se>
Date: Mon, 6 May 2024 22:03:38 +0200
context for pierre
Diffstat:
5 files changed, 39 insertions(+), 8 deletions(-)
diff --git a/Makefile b/Makefile
@@ -1,6 +1,6 @@
.SUFFIXES: .c .o .so
CC=clang
-CFLAGS+=-std=c99 -pedantic -Wall -Werror -Wstrict-prototypes
+CFLAGS+=-std=c11 -pedantic -Wall -Werror -Wstrict-prototypes
CFLAGS+=-Wmissing-prototypes -Wmissing-declarations -Wshadow
CFLAGS+=-Wpointer-arith -Wcast-qual -Wsign-compare
CFLAGS+=-O2 -g
diff --git a/pierre.c b/pierre.c
@@ -1,4 +1,5 @@
#include <fmpz.h>
+#include <fmpz_vec.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
@@ -6,7 +7,19 @@
#include "pierre.h"
void
-fermat_factor(fmpz_t r, fmpz_t n, size_t limit)
+fermat_ctx_init(fermat_ctx *ctx)
+{
+ ctx->zs = _fmpz_vec_init(FERMAT_CTX_NZS);
+}
+
+void
+fermat_ctx_clear(fermat_ctx *ctx)
+{
+ _fmpz_vec_clear(ctx->zs, FERMAT_CTX_NZS);
+}
+
+void
+fermat_factor(fermat_ctx *ctx, fmpz_t r, fmpz_t n, size_t limit)
{
size_t i;
uint64_t inc = 1;
@@ -24,13 +37,12 @@ fermat_factor(fmpz_t r, fmpz_t n, size_t limit)
}
if (found) {
- fmpz_t tmp;
- fmpz_init_set(tmp, n);
+ fmpz_t tmp = {ctx->zs[0]};
+ fmpz_set(tmp, n);
fmpz_sub(tmp, r, n); // tmp = b^2
fmpz_sqrt(tmp, tmp); // tmp = b
fmpz_sqrt(r, r); // r = a
fmpz_add(r, r, tmp);
- fmpz_clear(tmp);
} else {
fmpz_set_ui(r, 0);
}
diff --git a/pierre.h b/pierre.h
@@ -1,6 +1,15 @@
#ifndef _PIERRE_H_
#define _PIERRE_H_
+#define FERMAT_CTX_NZS 1
+
+typedef struct __fermat_ctx {
+ fmpz* zs;
+} fermat_ctx;
+
+void fermat_ctx_init(fermat_ctx *ctx);
+void fermat_ctx_clear(fermat_ctx *ctx);
+
/**
* Fermat factorisation of an integer.
*
@@ -10,10 +19,11 @@
* is a perfect square for some i in [1, limit]. If no factor is found
* it sets res to 0.
*
+ * @param ctx fermat factoring context
* @param res the output fmpz_t
* @param n the number to attempt to Fermat factorise
* @param limit iteration limit bound
*/
-void fermat_factor(fmpz_t r, fmpz_t n, size_t limit);
+void fermat_factor(fermat_ctx *ctx, fmpz_t r, fmpz_t n, size_t limit);
#endif
diff --git a/test_angrepp.c b/test_angrepp.c
@@ -41,15 +41,20 @@ static void
test_pierre_factor(void)
{
fmpz_t n, r;
+ fermat_ctx ctx;
+
+ fermat_ctx_init(&ctx);
fmpz_init(n);
fmpz_init(r);
+
fmpz_set_str(n, "13957163057215389251", 10);
- fermat_factor(r, n, 200);
+ fermat_factor(&ctx, r, n, 200);
assert(fmpz_divisible(n, r));
assert(fmpz_cmp_ui(r, 1) > 0);
+ fermat_ctx_clear(&ctx);
fmpz_clear(n);
fmpz_clear(r);
}
diff --git a/tools/pierre.c b/tools/pierre.c
@@ -12,15 +12,19 @@ int
main(void)
{
fmpz_t read, factor;
+ fermat_ctx ctx;
+
+ fermat_ctx_init(&ctx);
fmpz_init(factor);
fmpz_init(read);
while (read_next_hex_fmpz(read) == 0) {
- fermat_factor(factor, read, DEFAULT_LIMIT);
+ fermat_factor(&ctx, factor, read, DEFAULT_LIMIT);
fmpz_print(factor);
printf("\n");
}
+ fermat_ctx_clear(&ctx);
fmpz_clear(factor);
fmpz_clear(read);