From 8c927a1764e4a985179f9f93d266ee3b84d21422 Mon Sep 17 00:00:00 2001
From: Paul Zimmermann <Paul.Zimmermann@inria.fr>
Date: Wed, 26 Jun 2024 09:49:16 +0200
Subject: [PATCH] fixed https://gitlab.inria.fr/zimmerma/ecm/-/issues/21876

---
 parametrizations.c | 10 +++++++---
 test.ecm           |  3 +++
 2 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/parametrizations.c b/parametrizations.c
index 7b15e8c5..44249024 100644
--- a/parametrizations.c
+++ b/parametrizations.c
@@ -425,11 +425,15 @@ int
 get_curve_from_random_parameter (mpz_t f, mpres_t A, mpres_t x, mpz_t sigma, 
                                  int param, mpmod_t modulus, gmp_randstate_t rng)
 {
-  int ret;
+  int ret = ECM_ERROR;
 
   /* initialize the random number generator if not already done */
   init_randstate (rng);
-  do
+  /* we perform only a fixed number of tries to find a suitable curve,
+     to avoid an infinite loop in corner cases (for example with -param 1,
+     there is no valid sigma for n=3, see
+     https://gitlab.inria.fr/zimmerma/ecm/-/issues/21876) */
+  for (int i = 0; ret == ECM_ERROR && i < 10; i++)
     {
       if (param == ECM_PARAM_SUYAMA)
         {
@@ -453,7 +457,7 @@ get_curve_from_random_parameter (mpz_t f, mpres_t A, mpres_t x, mpz_t sigma,
         }
       else
         return ECM_ERROR;
-    } while (ret == ECM_ERROR);
+    }
 
   return ret;
 }
diff --git a/test.ecm b/test.ecm
index eff5ab57..07c1e9b4 100755
--- a/test.ecm
+++ b/test.ecm
@@ -534,6 +534,9 @@ checkcode $? 0
 echo 18446744073709551557 | $ECM -param 1 -A 312656731337392125 11000
 checkcode $? 8
 
+# non-regression test for https://gitlab.inria.fr/zimmerma/ecm/-/issues/21876
+echo 3 | $ECM -param 1 1000 1000; checkcode $? 1
+
 # test -bsaves/-bloads
 TEST=test.ecm.s$$
 echo 18446744073709551557 | $ECM -param 1 -A 1 -bsaves $TEST 11000
-- 
GitLab