/* Choice of best parameters for stage 2.

Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2010 Paul Zimmermann,
Alexander Kruppa, Dave Newman.

This file is part of the ECM Library.

The ECM Library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at your
option) any later version.

The ECM Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
License for more details.

You should have received a copy of the GNU Lesser General Public License
along with the ECM Library; see the file COPYING.LIB.  If not, see
http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */

#include <stdio.h>
#include <gmp.h>
#include "ecm-impl.h"

/*
  Compute (d, d2, k) such that:
  (0) k >= k0
  (1) d is a multiple of 6
  (2) k * d * (eulerphi(d)/2) * d2 / eulerphi(d2) >= B2 - B2min
  (3) gcd(d, d2) == 1
  (4) k is minimal, subject to previous conditions
  (5) if parameter po2 is != 0, rounds dF up to a power of 2
  Return non-zero iff an error occurred (too large step 2 bound).
 */

/* How we test whether given d,d2,dF,k,i0 parameters cover the desired 
   B2min-B2 range:

   In stage 2 we generate all values  p = f(i * d) +- f(j * d2)  with 

     1. gcd (i, d2) == 1, 
     2. gcd (j, d) == 1,
     3. j == 1 (mod 6),
     4. 6|d
     5. 1 <= j <= d - 5, (it's -5, not just -1, because of 3. and 4.)
     6. i0 <= i <= i1
     7. gcd (d, d2) == 1
   
   where f(x) is x^S or the S-th Dickson polynomial g_{S,-1}(x). Extra 
   factors included by S>1 are not considered in this analysis, we assume 
   S=1, f(x)=x so that  p = i * d +- j * d2.

   (Note: i values greater than stated in 3. may be generated if we have 
    to round up dF, for example to a power of 2. However, the root generation
    code can put anything it likes in those extra roots, so we make no 
    assumption here that this will extend the range of the i values.)
   
   Hence the values at the high end of the stage 2 range that are not 
   generated are
   
     p = (i1 + n) * d +- j * d2, n > 0

   and the smallest one of those is
   
     p = (i1 + 1) * d - (d - 5) * d2
       = d * (i1 - d2 + 1) + 5 * d2
   
   At the low end of stage 2, values not generated are
   
     p = (i0 - n) * d +- j * d2, n > 0   

   the largest one being
   
     p = (i0 - 1) * d + (d - 5) * d2
       = d * (i0 + d2 - 1) - 5*d2

   Thus, values p that are coprime do d*d2 and 
     d * (i0 + d2 - 1) - 5*d2 + 1 <= p <= d * (i1 - d2 + 1) + 5 * d2 - 1 
   are included in stage 2.

   
   The number of roots of G we compute is k * dF. For d2 == 1, this means 
   i1 = i0 + k * dF - 1  (-1 because both i0 and i1 are included).

   For d2 > 1, values j not coprime to d2 are skipped (see condition 1).
   The number of values in [1, i0] that are not coprime to d2 (with d2 prime) 
   is floor (i0 / d2); in [1, i1] it is floor (i1 / d2). 
   So we require that
   k * dF >= i1 - i0 + 1 - (floor (i1 / d2) - floor (i0 / d2))
   
   
*/

int
bestD (root_params_t *root_params, unsigned long *finalk, 
       unsigned long *finaldF, mpz_t B2min, mpz_t B2, int po2, int use_ntt, 
       double maxmem, int treefile, mpmod_t modulus)
{
/* the following list contains successive values of b with
   increasing values of eulerphi(b). It was generated by the following 
   Maple program:
l := [[1,1]]:
for b from 12 by 6 do
   d:=numtheory[phi](b)/2;
   while d <= l[nops(l)][2] do l:=subsop(nops(l)=NULL, l) od;
   n := nops(l);
   if b>1.1*l[n][1] then l := [op(l), [b,d]]; lprint(l) fi;
od:
*/
#define N 109
  static unsigned int l[N] = {12, 18, 30, 42, 60, 90, 120, 150, 210, 240, 270, 330, 420, 510, 630, 840, 1050, 1260, 1470, 1680, 1890, 2310, 2730, 3150, 3570, 3990, 4620, 5460, 6090, 6930, 8190, 9240, 10920, 12180, 13860, 16170, 18480, 20790, 23100, 30030, 34650, 39270, 43890, 48510, 60060, 66990, 78540, 90090, 99330, 120120, 133980, 150150, 180180, 210210, 240240, 270270, 300300, 334950, 371280, 420420, 510510, 570570, 600600, 630630, 746130, 870870, 1021020, 1141140, 1291290, 1531530, 1711710, 1891890, 2081310, 2312310, 2552550, 2852850, 3183180, 3573570, 3993990, 4594590, 5105100, 5705700, 6322470, 7147140, 7987980, 8978970, 10210200, 11741730, 13123110, 14804790, 16546530, 19399380, 21411390, 23993970, 26816790, 29609580, 33093060, 36606570, 40330290, 44414370, 49639590, 54624570, 60090030, 67897830, 77597520, 87297210, 96996900, 107056950, 118107990};
#define Npo2 23
  static unsigned int lpo2[Npo2] = {12, 30, 60, 120, 240, 510, 1020, 2310, 
                                 4620, 9240, 19110, 39270, 79170, 158340, 
                                 324870, 690690, 1345890, 2852850, 5705700, 
                                 11741730, 23130030, 48498450, 96996900};

  unsigned long i, d1 = 0, d2 = 0, dF = 0, phid, k, maxN;
  mpz_t j, t, i0, i1;
  int r = 0;

  if (mpz_cmp (B2, B2min) < 0)
    {
      /* No stage 2. Set relevant parameters to 0. Leave B2, B2min the same */
      *finalk = 0;
      *finaldF = 0;
      return 0;
    }
  
  mpz_init (i0);
  mpz_init (i1);
  mpz_init (j);
  mpz_init (t);
  k = *finalk; /* User specified k value passed in via finalk */

  /* Look for largest dF we can use while satisfying the maxmem parameter */
  maxN = (po2) ? Npo2 : N;
  if (maxmem != 0.)
  {
    for (i = 0; i < maxN; i++)
      {
        int lg_dF, sp_num = 0;
        double memory;
        
        d1 = (po2) ? lpo2[i] : l[i];
        phid = eulerphi (d1) / 2;
        dF = (po2) ? 1U << ceil_log2 (phid) : phid;
        lg_dF = ceil_log2 (dF);
        
        if (use_ntt)
          sp_num = (2 * mpz_sizeinbase (modulus->orig_modulus, 2) + lg_dF) / 
                 SP_NUMB_BITS + 4;
        
	memory = memory_use (dF, sp_num, (treefile) ? 0 : lg_dF, modulus);
        outputf (OUTPUT_DEVVERBOSE,
                 "Estimated mem for dF = %lu, sp_num = %d: %.0f\n",
                 dF, sp_num, memory);
        if (memory > maxmem)
          break;
      }
    maxN = i;
  }      
  
  for (i = 0; i < maxN; i++)
    {
      d1 = (po2) ? lpo2[i] : l[i];
      phid = eulerphi (d1) / 2;
      dF = (po2) ? 1U << ceil_log2 (phid) : phid;
      /* Look for smallest prime < 25 that does not divide d1 */
      /* The caller can force d2 = 1 by setting root_params->d2 != 0 */
      d2 = 1;
      if (root_params->d2 == 0)
        for (d2 = 5; d2 < 25; d2 += 2)
          {
            if (d2 % 3 == 0)
              continue;
            if (d1 % d2 > 0)
              break;
          }

      if (d2 >= 25 || d2 - 1 > dF)
        d2 = 1;

#if 0
      /* The code to init roots of G can handle negative i0 now. */
      if (d2 > 1 && mpz_cmp_ui (B2min, (d1 - 1) * d2 - d1) <= 0) 
        d2 = 1; /* Would make i0 < 0 */
#endif
      
      mpz_set_ui (i0, d1 - 1);
      mpz_mul_ui (i0, i0, d2);
      mpz_set (j, B2);
      mpz_add (i1, j, i0); /* i1 = B2 + (d1 - 1) * d2 */
      mpz_set (j, B2min);
      mpz_sub (i0, j, i0); /* i0 = B2min - (d1 - 1) * d2 */
      mpz_cdiv_q_ui (i0, i0, d1); /* i0 = ceil ((B2min - (d1 - 1) * d2) / d1) */
      mpz_fdiv_q_ui (i1, i1, d1); /* i1 = floor ((B2 + (d1 - 1) * d2) / d1) */
      
      /* How many roots of G will we need ? */
      mpz_sub (j, i1, i0);
      mpz_add_ui (j, j, 1);

      /* Integer multiples of d2 are skipped (if d2 > 1) */
      if (d2 > 1)
        {
          mpz_fdiv_q_ui (t, i1, d2);
          mpz_sub (j, j, t);
          mpz_fdiv_q_ui (t, i0, d2);
          mpz_add (j, j, t); /* j -= floor (i1 / d2) - floor (i0 / d2) */
        }
      
      /* How many blocks will we need ? Divide lines by dF, rounding up */
      mpz_cdiv_q_ui (j, j, dF);
      
      if ((k != ECM_DEFAULT_K && mpz_cmp_ui (j, k) <= 0) || 
          (k == ECM_DEFAULT_K && mpz_cmp_ui (j, (po2) ? 6 : 2) <= 0))
        break;
    }

  if (i == maxN)
    {
      if (k != ECM_DEFAULT_K)
        {
          /* The user asked for a specific k and we couldn't satisfy the
             condition. Nothing we can do ... */
          outputf (OUTPUT_ERROR, "Error: too large step 2 bound, increase -k\n");
          r = ECM_ERROR;
          goto clear_and_exit;
        }
      else if (!mpz_fits_ulong_p (j))
        {
          /* Can't fit the number of blocks in an unsigned long. Nothing we
             can do ... */
          outputf (OUTPUT_ERROR, "Error: stage 2 interval too large, cannot "
                   "generate suitable parameters.\nTry a smaller B2 value.\n");
          r = ECM_ERROR;
          goto clear_and_exit;
        }
      if (maxN == 0)
        {
          /* We can't do a stage 2 at all with the memory the user allowed.
             Nothing we can do ... */
          outputf (OUTPUT_ERROR, "Error: stage 2 not possible with memory "
                   "allowed by -maxmem.\n");
          r = ECM_ERROR;
          goto clear_and_exit;
        }
      /* else: We can fit the number of blocks into an unsigned int, so we use 
         it. This may be a very large value for huge B2-B2min, the user
         is going to notice sooner or later */
    }
  
  /* If the user specified a number of blocks, we'll use that no matter what.
     Since j may be smaller than k, this may increase the B2 limit */
  if (k == ECM_DEFAULT_K)
    k = mpz_get_ui (j);

  /* Now that we have the number of blocks, compute real i1. There will be
     k * dF roots of G computed, starting at i0, skipping all that are not
     coprime to d2. While d2 is prime, that means: are not multiples of d2.
     Hence we want i1 so that 
       i1 - floor(i1 / d2) - i0 + ceil((i0 / d2) == k * dF
       i1 - floor(i1 / d2) == k * dF + i0 - ceil((i0 / d2)
  */
  
  mpz_set_ui (j, k);
  mpz_mul_ui (j, j, dF);
  if (d2 == 1)
    {
      mpz_add (i1, i0, j);
      mpz_sub_ui (i1, i1, 1);
    }
  else
    {
      mpz_add (j, j, i0);
      mpz_cdiv_q_ui (t, i0, d2);
      mpz_sub (j, j, t); /* j = k * dF + i0 - ceil((i0 / d2) */
      mpz_fdiv_qr_ui (j, t, j, d2 - 1);
      mpz_mul_ui (j, j, d2);
      mpz_add (i1, j, t);
    }

  root_params->d1 = d1;
  root_params->d2 = d2;
  mpz_set (root_params->i0, i0);
  *finaldF = dF;
  *finalk = k;

  /* We want B2' the largest integer that satisfies 
     i1 = floor ((B2' + (d1 - 1) * d2) / d1)
        = floor ((B2'-d2)/d1) + d2
     i1 - d2 = floor ((B2'-d2)/d1)
     (B2'-d2)/d1 < i1-d2+1
     B2'-d2 < (i1-d2+1) * d1
     B2' < (i1-d2+1) * d1 + d2
     B2' = (i1-d2+1) * d1 + d2 - 1
  */
  
  mpz_sub_ui (i1, i1, d2 - 1);
  mpz_mul_ui (B2, i1, d1);
  mpz_add_ui (B2, B2, d2 - 1);

clear_and_exit:
  mpz_clear (t);
  mpz_clear (j);
  mpz_clear (i1);
  mpz_clear (i0);

  return r;
}
