sieve.c
上传用户:zbbssh
上传日期:2007-01-08
资源大小:196k
文件大小:21k
源码类别:

CA认证

开发平台:

C/C++

  1. /*
  2.  * sieve.c - Trial division for prime finding.
  3.  *
  4.  * Copyright (c) 1995  Colin Plumb.  All rights reserved.
  5.  * For licensing and other legal details, see the file legal.c.
  6.  *
  7.  * Finding primes:
  8.  * - Sieve 1 to find the small primes for
  9.  * - Sieve 2 to find the candidate large primes, then
  10.  * - Pseudo-primality test.
  11.  *
  12.  * An important question is how much trial division by small primes
  13.  * should we do?  The answer is a LOT.  Even a heavily optimized
  14.  * Fermat test to the base 2 (the simplest pseudoprimality test)
  15.  * is much more expensive than a division.
  16.  *
  17.  * For an prime of n k-bit words, a Fermat test to the base 2 requires n*k
  18.  * modular squarings, each of which involves n*(n+1)/2 signle-word multiplies
  19.  * in the squaring and n*(n+1) multiplies in the modular reduction, plus
  20.  * some overhead to get into and out of Montgomery form.  This is a total
  21.  * of 3/2 * k * n^2 * (n+1).  Equivalently, if n*k = b bits, it's
  22.  * 3/2 * (b/k+1) * b^2 / k.
  23.  *
  24.  * A modulo operation requires n single-word divides.  Let's assume that
  25.  * a divide is 4 times the cost of a multiply.  That's 4*n multiplies.
  26.  * However, you only have to do the division once for your entire
  27.  * search.  It can be amortized over 10-15 primes.  So it's
  28.  * really more like n/3 multiplies.  This is b/3k.
  29.  *
  30.  * Now, let's suppose you have a candidate prime t.  Your options
  31.  * are to a) do trial division by a prime p, then do a Fermat test,
  32.  * or to do the Fermat test directly.  Doing the trial division
  33.  * costs b/3k multiplies, but a certain fraction of the time (1/p), it
  34.  * saves you 3/2 b^3 / k^2 multiplies.  Thus, it's worth it doing the
  35.  * division as long as b/3k < 3/2 * (b/k+1) * b^2 / k / p.
  36.  * I.e. p < 9/2 * (b/k + 1) * b = 9/2 * (b^2/k + b).
  37.  * E.g. for k=16 and b=256, p < 9/2 * 17 * 256 = 19584.
  38.  * Solving for k=16 and k=32 at a few interesting value of b:
  39.  *
  40.  * k=16, b=256: p <  19584 k=32, b=256: p <  10368
  41.  * k=16, b=384: p <  43200 k=32, b=384; p <  22464
  42.  * k=16, b=512: p <  76032 k=32, b=512: p <  39168
  43.  * k=16, b=640: p < 118080 k=32, b=640: p <  60480
  44.  *
  45.  * H'm... before using the highly-optimized Fermat test, I got much larger
  46.  * numbers (64K to 256K), and designed the sieve for that.  Maybe it needs
  47.  * to be reduced.  It *is* true that the desirable sieve size increases
  48.  * rapidly with increasing prime size, and it's the larger primes that are
  49.  * worrisome in any case.  I'll leave it as is (64K) for now while I
  50.  * think about it.
  51.  *
  52.  * A bit of tweaking the division (we can compute a reciprocal and do
  53.  * multiplies instead, turning 4*n into 4 + 2*n) would increase all the
  54.  * numbers by a factor of 2 or so.
  55.  *
  56.  *
  57.  * Bit k in a sieve corresponds to the number a + k*b.
  58.  * For a given a and b, the sieve's job is to find the values of
  59.  * k for which a + k*b == 0 (mod p).  Multiplying by b^-1 and
  60.  * isolating k, you get k == -a*b^-1 (mod p).  So the values of
  61.  * k which should be worked on are k = (-a*b^-1 mod p) + i * p,
  62.  * for i = 0, 1, 2,...
  63.  *
  64.  * Note how this is still easy to use with very large b, if you need it.
  65.  * It just requires computing (b mod p) and then finding the multiplicative
  66.  * inverse of that.
  67.  *
  68.  *
  69.  * How large a space to search to ensure that one will hit a prime?
  70.  * The average density is known, but the primes behave oddly, and sometimes
  71.  * there are large gaps.  It is conjectured by shanks that the first gap
  72.  * of size "delta" will occur at approximately exp(sqrt(delta)), so a delta
  73.  * of 65536 is conjectured to be to contain a prime up to e^256.
  74.  * Remembering the handy 2<->e conversion ratios:
  75.  * ln(2) = 0.693147   log2(e) = 1.442695
  76.  * This covers up to 369 bits.  Damn, not enough!  Still, it'll have to do.
  77.  *
  78.  * Cramer's conjecture (he proved it for "most" cases) is that in the limit,
  79.  * as p goes to infinity, the largest gap after a prime p tends to (ln(p))^2.
  80.  * So, for a 1024-bit p, the interval to the next prime is expected to be
  81.  * about 709.78^2, or 503791.  We'd need to enlarge our space by a factor of
  82.  * 8 to be sure.  It isn't worth the hassle.
  83.  *
  84.  * Note that a span of this size is expected to contain 92 primes even
  85.  * in the vicinity of 2^1024 (it's 369 at 256 bits and 492 at 192 bits).
  86.  * So the probability of failure is pretty low.
  87.  */
  88. #if HAVE_CONFIG_H
  89. #include "config.h"
  90. #endif
  91. #if !NO_ASSERT_H
  92. #include <assert.h>
  93. #else
  94. #define assert(x) (void)0
  95. #endif
  96. #if HAVE_LIMITS_H
  97. #include <limits.h> /* For UINT_MAX */
  98. #endif /* If not avail, default value of 0 is safe */
  99. #if HAVE_STRING_H
  100. #include <string.h> /* for memset() */
  101. #elif HAVE_STRINGS_H
  102. #include <strings.h>
  103. #endif
  104. #if NEED_MEMORY_H
  105. #include <memory.h>
  106. #endif
  107. #include "bn.h"
  108. #include "sieve.h"
  109. #ifdef MSDOS
  110. #include "lbnmem.h"
  111. #endif
  112. #include "kludge.h"
  113. /*
  114.  * Each array stores potential primes as 1 bits in little-endian bytes.
  115.  * Bit k in an array represents a + k*b, for some parameters a and b
  116.  * of the sieve.  Currently, b is hardcoded to 2.
  117.  *
  118.  * Various factors of 16 arise because these are all *byte* sizes, and
  119.  * skipping even numbers, 16 numbers fit into a byte's worth of bitmap.
  120.  */
  121. /*
  122.  * The first number in the small prime sieve.  This could be raised to 3
  123.  * if you want to squeeze bytes bytes out aggressively for a smaller SMALL
  124.  * table, and doing so would let one more prime into the end of the array,
  125.  * but there is no sense making it larger if you're generating small primes
  126.  * up to the limit if 2^16, since it doesn't save any memory and would
  127.  * require extra code to ignore 65537 in the last byte, which is over the
  128.  * 16-bit limit.
  129.  */
  130. #define SMALLSTART 1
  131. /*
  132.  * Size of sieve used to find large primes, in bytes.  For compatibility
  133.  * with 16-bit-int systems, the largest prime that can appear in it,
  134.  * SMALL * 16 + SMALLSTART - 2, must be < 65536.  Since 65537 is a prime,
  135.  * this is the absolute maximum table size.
  136.  */
  137. #define SMALL (65536/16)
  138. /*
  139.  * Compute the multiplicative inverse of x, modulo mod, using the extended
  140.  * Euclidean algorithm.  The classical EEA returns two results, traditionally
  141.  * named s and t, but only one (t) is needed or computed here.
  142.  * It is unrolled twice to avoid some variable-swapping, and because negating
  143.  * t every other round makes all the number positive and less than the
  144.  * modulus, which makes fixed-length arithmetic easier.
  145.  *
  146.  * If gcd(x, mod) != 1, then this will return 0.
  147.  */
  148. static unsigned
  149. sieveModInvert(unsigned x, unsigned mod)
  150. {
  151. unsigned y;
  152. unsigned t0, t1;
  153. unsigned q;
  154. if (x <= 1)
  155. return x; /* 0 and 1 are self-inverse */
  156. /*
  157.  * The first round is simplified based on the
  158.  * initial conditions t0 = 1 and t1 = 0.
  159.  */
  160. t1 = mod / x;
  161. y = mod % x;
  162. if (y <= 1)
  163. return y ? mod - t1 : 0;
  164. t0 = 1;
  165. do {
  166. q = x / y;
  167. x = x % y;
  168. t0 += q * t1;
  169. if (x <= 1)
  170. return x ? t0 : 0;
  171. q = y / x;
  172. y = y % x;
  173. t1 += q * t0;
  174. } while (y > 1);
  175. return y ? mod - t1 : 0;
  176. }
  177. /*
  178.  * Perform a single sieving operation on an array.  Clear bits
  179.  * "start", "start+step", "start+2*step", etc. from the array,
  180.  * up to the size limit (in BYTES) "size".  All of the arguments
  181.  * must fit into 16 bits for portability.
  182.  *
  183.  * This is the core of the sieving operation.  In addition to being
  184.  * called from the sieving functions, it is useful to call directly
  185.  * if, say, you want to exclude primes congruent to 1 mod 3, or
  186.  * whatever.  (Although in that case, it would be better to change
  187.  * the sieving to use a step size of 6 and start == 5 (mod 6).)
  188.  *
  189.  * Originally, this was inlined in the code below (with various checks
  190.  * turned off where they could be inferred from the environment), but
  191.  * it turns out that all the sieving is so fast that it makes a
  192.  * negligible speed difference and smaller, cleaner code was preferred.
  193.  *
  194.  * Rather than increment a bit index through the array and clear
  195.  * the corresponding bit, this code takes advantage of the fact that
  196.  * every eighth increment must use the same bit position in a byte.
  197.  * I.e. start + k*step == start + (k+8)*step (mod 8).  Thus, a
  198.  * bitmask can be computed only eight times and used for all multiples.
  199.  * Thus, the outer loop is over (k mod 8) while the inner loop is
  200.  * over (k div 8).
  201.  *
  202.  * The only further trickiness is that this code is designed to accept
  203.  * start, step, and size up to 65535 on 16-bit machines.  On such
  204.  * a machine, the computation "start+step" can overflow, so we need
  205.  * to insert an extra check for that situation.
  206.  */
  207. void
  208. sieveSingle(unsigned char *array, unsigned size, unsigned start, unsigned step)
  209. {
  210. unsigned bit;
  211. unsigned char mask;
  212. unsigned i;
  213. #if UINT_MAX < 0x1ffff
  214. /* Unsigned is small; add checks for wrap */
  215. for (bit = 0; bit < 8; bit++) {
  216. i = start/8;
  217. if (i >= size)
  218. break;
  219. mask = ~(1 << (start & 7));
  220. do {
  221. array[i] &= mask;
  222. i += step;
  223. } while (i >= step && i < size);
  224. start += step;
  225. if (start < step) /* Overflow test */
  226. break;
  227. }
  228. #else
  229. /* Unsigned has the range - no overflow possible */
  230. for (bit = 0; bit < 8; bit++) {
  231. i = start/8;
  232. if (i >= size)
  233. break;
  234. mask = ~(1 << (start & 7));
  235. do {
  236. array[i] &= mask;
  237. i += step;
  238. } while (i < size);
  239. start += step;
  240. }
  241. #endif
  242. }
  243. /*
  244.  * Returns the index of the next bit set in the given array.
  245.  * The search begins after the specified bit, so if you care
  246.  * about bit 0, you need to check it explicitly yourself.
  247.  * This returns 0 if no bits are found.
  248.  *
  249.  * Note that the size is in bytes, and that it takes and returns
  250.  * BIT positions.  If the array represents odd numbers only,
  251.  * as usual, the returns values must be doubled to turn them into
  252.  * offsets from the initial number.
  253.  */
  254. unsigned
  255. sieveSearch(unsigned char const *array, unsigned size, unsigned start)
  256. {
  257. unsigned i; /* Loop index */
  258. unsigned char t; /* Temp */
  259. if (!++start)
  260. return 0;
  261. i = start/8;
  262. if (i >= size)
  263. return 0; /* Done! */
  264. /* Deal with odd-bit beginnings => search the first byte */
  265. if (start & 7) {
  266. t = array[i++] >> (start & 7);
  267. if (t) {
  268. if (!(t & 15)) {
  269. t >>= 4;
  270. start += 4;
  271. }
  272. if (!(t & 3)) {
  273. t >>= 2;
  274. start += 2;
  275. }
  276. if (!(t & 1))
  277. start += 1;
  278. return start;
  279. } else if (i == size) {
  280. return 0; /* Done */
  281. }
  282. }
  283. /* Now the main search loop */
  284. do {
  285. if ((t = array[i]) != 0) {
  286. start = 8*i;
  287. if (!(t & 15)) {
  288. t >>= 4;
  289. start += 4;
  290. }
  291. if (!(t & 3)) {
  292. t >>= 2;
  293. start += 2;
  294. }
  295. if (!(t & 1))
  296. start += 1;
  297. return start;
  298. }
  299. } while (++i < size);
  300. /* Failed */
  301. return 0;
  302. }
  303. /*
  304.  * Build a table of small primes for sieving larger primes with.
  305.  * This could be cached between calls to sieveBuild, but it's so
  306.  * fast that it's really not worth it.  This code takes a few
  307.  * milliseconds to run.
  308.  */
  309. static void
  310. sieveSmall(unsigned char *array, unsigned size)
  311. {
  312. unsigned i; /* Loop index */
  313. unsigned p; /* The current prime */
  314. /* Initialize to all 1s */
  315. memset(array, 0xFF, size);
  316. #if SMALLSTART == 1
  317. /* Mark 1 as NOT prime */
  318. array[0] = 0xfe;
  319. i = 1; /* Index of first prime */
  320. #else
  321. i = 0; /* Index of first prime */
  322. #endif
  323. /*
  324.  * Okay, now sieve via the primes up to 256, obtained from the
  325.  * table itself.  We know the maximum possible table size
  326.  * is 65536, and sieveSingle() can cope with out-of-range inputs
  327.  * safely, and the time required is trivial, so it isn't adaptive
  328.  * based on the array size.
  329.  *
  330.  * Convert each bit position into a prime, compute a starting
  331.  * sieve position (the square of the prime), and remove multiples
  332.  * from the table, using sieveSingle().  I used to have that code
  333.  * in line here, but the speed difference was so small it wasn't
  334.  * worth it.  If a compiler really wants to waste memory, it
  335.  * can inline it.
  336.  */
  337. do {
  338. p = 2 * i + SMALLSTART;
  339. if (p > 256)
  340. break;
  341. /* Start at square of p */
  342. sieveSingle(array, size, (p*p-SMALLSTART)/2, p);
  343. /* And find the next prime */
  344. i = sieveSearch(array, 16, i);
  345. } while (i);
  346. }
  347. /*
  348.  * This is the primary sieving function.  It fills in the array with
  349.  * a sieve (multiples of small primes removed) beginning at bn and
  350.  * proceeding in steps of "step".
  351.  *
  352.  * It generates a small array to get the primes to sieve by.  It's
  353.  * generated on the fly - sieveSmall is fast enough to make that
  354.  * perfectly acceptable.
  355.  *
  356.  * The caller should take the array, walk it with sieveSearch, and
  357.  * apply a stronger primality test to the numbers that are returned.
  358.  *
  359.  * If the "dbl" flag non-zero (at least 1), this also sieves 2*bn+1, in
  360.  * steps of 2*step.  If dbl is 2 or more, this also sieve 4*bn+3,
  361.  * in steps of 4*step, and so on for arbitrarily high values of "dbl".
  362.  * This is convenient for finding primes such that (p-1)/2 is also prime.
  363.  * This is particularly efficient because sieveSingle is controlled by the
  364.  * parameter s = -n/step (mod p).  (In fact, we find t = -1/step (mod p)
  365.  * and multiply that by n (mod p).)  If you have -n/step (mod p), then
  366.  * finding -(2*n+1)/(2*step) (mod p), which is -n/step - 1/(2*step) (mod p),
  367.  * reduces to finding -1/(2*step) (mod p), or t/2 (mod p), and adding that
  368.  * to s = -n/step (mod p).  Dividing by 2 modulo an odd p is easy -
  369.  * if even, divide directly.  Otherwise, add p (which produces an even
  370.  * sum), and divide by 2.  Very simple.  And this produces s' and t'
  371.  * for step' = 2*step.  It can be repeated for step'' = 4*step and so on.
  372.  *
  373.  * Note that some of the math is complicated by the fact that 2*p might
  374.  * not fit into an unsigned, so rather than if (odd(x)) x = (x+p)/2,
  375.  * we do if (odd(x)) x = x/2 + p/2 + 1;
  376.  *
  377.  * TODO: Do the double-sieving by sieving the larger number, and then
  378.  * just subtract one from the remainder to get the other parameter.
  379.  * (bn-1)/2 is divisible by an odd p iff bn-1 is divisible, which is true
  380.  * iff bn == 1 mod p.  This requires using a step size of 4.
  381.  */
  382. int
  383. sieveBuild(unsigned char *array, unsigned size, struct BigNum const *bn,
  384. unsigned step, unsigned dbl)
  385. {
  386. unsigned i, j; /* Loop index */
  387. unsigned p; /* Current small prime */
  388. unsigned s; /* Where to start operations in the big sieve */
  389. unsigned t; /* Step modulo p, the current prime */
  390. #ifdef MSDOS /* Use dynamic allocation rather than on the stack */
  391. unsigned char *small;
  392. #else
  393. unsigned char small[SMALL];
  394. #endif
  395. assert(array);
  396. #ifdef MSDOS
  397. small = lbnMemAlloc(SMALL); /* Which allocator?  Not secure. */
  398. if (!small)
  399. return -1; /* Failed */
  400. #endif
  401. /*
  402.  * An odd step is a special case, since we must sieve by 2,
  403.  * which isn't in the small prime array and has a few other
  404.  * special properties.  These are:
  405.  * - Since the numbers are stored in binary, we don't need to
  406.  *   use bnModQ to find the remainder.
  407.  * - If step is odd, then t = step % 2 is 1, which allows
  408.  *   the elimination of a lot of math.  Inverting and negating
  409.  *   t don't change it, and multiplying s by 1 is a no-op,
  410.  *   so t isn't actually mentioned.
  411.  * - Since this is the first sieving, instead of calling
  412.  *   sieveSingle, we can just use memset to fill the array
  413.  *   with 0x55 or 0xAA.  Since a 1 bit means possible prime
  414.  *   (i.e. NOT divisible by 2), and the least significant bit
  415.  *   is first, if bn % 2 == 0, we use 0xAA (bit 0 = bn is NOT
  416.  *   prime), while if bn % 2 == 1, use 0x55.
  417.  *   (If step is even, bn must be odd, so fill the array with 0xFF.)
  418.  * - Any doublings need not be considered, since 2*bn+1 is odd, and
  419.  *   2*step is even, so none of these numbers are divisible by 2.
  420.  */
  421. if (step & 1) {
  422. s = bnLSWord(bn) & 1;
  423. memset(array, 0xAA >> s, size);
  424. } else {
  425. /* Initialize the array to all 1's */
  426. memset(array, 255, size);
  427. assert(bnLSWord(bn) & 1);
  428. }
  429. /*
  430.  * This could be cached between calls to sieveBuild, but
  431.  * it's really not worth it; sieveSmall is *very* fast.
  432.  * sieveSmall returns a sieve of odd primes.
  433.  */
  434. sieveSmall(small, SMALL);
  435. /*
  436.  * Okay, now sieve via the primes up to ssize*16+SMALLSTART-1,
  437.  * obtained from the small table.
  438.  */
  439. i = (small[0] & 1) ? 0 : sieveSearch(small, SMALL, 0);
  440. do {
  441. p = 2 * i + SMALLSTART;
  442. /*
  443.  * Modulo is usually very expensive, but step is usually
  444.  * small, so this conditional is worth it.
  445.  */
  446. t = (step < p) ? step : step % p;
  447. if (!t) {
  448. /*
  449.  * Instead of assert failing, returning all zero
  450.  * bits is the "correct" thing to do, but I think
  451.  * that the caller should take care of that
  452.  * themselves before starting.
  453.  */
  454. assert(bnModQ(bn, p) != 0);
  455. continue;
  456. }
  457. /*
  458.  * Get inverse of step mod p.  0 < t < p, and p is prime,
  459.  * so it has an inverse and sieveModInvert can't return 0.
  460.  */
  461. t = sieveModInvert(t, p);
  462. assert(t);
  463. /* Negate t, so now t == -1/step (mod p) */
  464. t = p - t;
  465. /* Now get the bignum modulo the prime. */
  466. s = bnModQ(bn, p);
  467. /* Multiply by t, the negative inverse of step size */
  468. #if UINT_MAX/0xffff < 0xffff
  469. s = (unsigned)(((unsigned long)s * t) % p);
  470. #else
  471. s = (s * t) % p;
  472. #endif
  473. /* s is now the starting bit position, so sieve */
  474. sieveSingle(array, size, s, p);
  475. /* Now do the double sieves as desired. */
  476. for (j = 0; j < dbl; j++) {
  477. /* Halve t modulo p */
  478. #if UINT_MAX < 0x1ffff
  479. t = (t & 1) ? p/2 + t/2 + 1 : t/2;
  480. /* Add t to s, modulo p with overflow checks. */
  481. s += t;
  482. if (s >= p || s < t)
  483. s -= p;
  484. #else
  485. if (t & 1)
  486. t += p;
  487. t /= 2;
  488. /* Add t to s, modulo p */
  489. s += t;
  490. if (s >= p)
  491. s -= p;
  492. #endif
  493. sieveSingle(array, size, s, p);
  494. }
  495. /* And find the next prime */
  496. } while ((i = sieveSearch(small, SMALL, i)) != 0);
  497. #ifdef MSDOS
  498. lbnMemFree(small, SMALL);
  499. #endif
  500. return 0; /* Success */
  501. }
  502. /*
  503.  * Similar to the above, but use "step" (which must be even) as a step size
  504.  * rather than a fixed value of 2.  If "step" has any small divisors other
  505.  * than 2, this will blow up.
  506.  *
  507.  * Returns -1 on out of memory (MSDOS only, actually), and -2
  508.  * if step is found to be non-prime.
  509.  */
  510. int
  511. sieveBuildBig(unsigned char *array, unsigned size, struct BigNum const *bn,
  512. struct BigNum const *step, unsigned dbl)
  513. {
  514. unsigned i, j; /* Loop index */
  515. unsigned p; /* Current small prime */
  516. unsigned s; /* Where to start operations in the big sieve */
  517. unsigned t; /* step modulo p, the current prime */
  518. #ifdef MSDOS /* Use dynamic allocation rather than on the stack */
  519. unsigned char *small;
  520. #else
  521. unsigned char small[SMALL];
  522. #endif
  523. assert(array);
  524. #ifdef MSDOS
  525. small = lbnMemAlloc(SMALL); /* Which allocator?  Not secure. */
  526. if (!small)
  527. return -1; /* Failed */
  528. #endif
  529. /*
  530.  * An odd step is a special case, since we must sieve by 2,
  531.  * which isn't in the small prime array and has a few other
  532.  * special properties.  These are:
  533.  * - Since the numbers are stored in binary, we don't need to
  534.  *   use bnModQ to find the remainder.
  535.  * - If step is odd, then t = step % 2 is 1, which allows
  536.  *   the elimination of a lot of math.  Inverting and negating
  537.  *   t don't change it, and multiplying s by 1 is a no-op,
  538.  *   so t isn't actually mentioned.
  539.  * - Since this is the first sieving, instead of calling
  540.  *   sieveSingle, we can just use memset to fill the array
  541.  *   with 0x55 or 0xAA.  Since a 1 bit means possible prime
  542.  *   (i.e. NOT divisible by 2), and the least significant bit
  543.  *   is first, if bn % 2 == 0, we use 0xAA (bit 0 = bn is NOT
  544.  *   prime), while if bn % 2 == 1, use 0x55.
  545.  *   (If step is even, bn must be odd, so fill the array with 0xFF.)
  546.  * - Any doublings need not be considered, since 2*bn+1 is odd, and
  547.  *   2*step is even, so none of these numbers are divisible by 2.
  548.  */
  549. if (bnLSWord(step) & 1) {
  550. s = bnLSWord(bn) & 1;
  551. memset(array, 0xAA >> s, size);
  552. } else {
  553. /* Initialize the array to all 1's */
  554. memset(array, 255, size);
  555. assert(bnLSWord(bn) & 1);
  556. }
  557. /*
  558.  * This could be cached between calls to sieveBuild, but
  559.  * it's really not worth it; sieveSmall is *very* fast.
  560.  * sieveSmall returns a sieve of the odd primes.
  561.  */
  562. sieveSmall(small, SMALL);
  563. /*
  564.  * Okay, now sieve via the primes up to ssize*16+SMALLSTART-1,
  565.  * obtained from the small table.
  566.  */
  567. i = (small[0] & 1) ? 0 : sieveSearch(small, SMALL, 0);
  568. do {
  569. p = 2 * i + SMALLSTART;
  570. t = bnModQ(step, p);
  571. if (!t) {
  572. assert(bnModQ(bn, p) != 0);
  573. continue;
  574. }
  575. /* Get negative inverse of step */
  576. t = sieveModInvert(bnModQ(step, p), p);
  577. assert(t);
  578. t = p-t;
  579. /* Okay, we have a prime - get the remainder */
  580. s = bnModQ(bn, p);
  581. /* Now multiply s by the negative inverse of step (mod p) */
  582. #if UINT_MAX < 0xffff * 0xffff
  583. s = (unsigned)(((unsigned long)s * t) % p);
  584. #else
  585. s = (s * t) % p;
  586. #endif
  587. /* We now have the starting bit pos */
  588. sieveSingle(array, size, s, p);
  589. /* Now do the double sieves as desired. */
  590. for (j = 0; j < dbl; j++) {
  591. /* Halve t modulo p */
  592. #if UINT_MAX < 0x1ffff
  593. t = (t & 1) ? p/2 + t/2 + 1 : t/2;
  594. /* Add t to s, modulo p with overflow checks. */
  595. s += t;
  596. if (s >= p || s < t)
  597. s -= p;
  598. #else
  599. if (t & 1)
  600. t += p;
  601. t /= 2;
  602. /* Add t to s, modulo p */
  603. s += t;
  604. if (s >= p)
  605. s -= p;
  606. #endif
  607. sieveSingle(array, size, s, p);
  608. }
  609. /* And find the next prime */
  610. } while ((i = sieveSearch(small, SMALL, i)) != 0);
  611. #ifdef MSDOS
  612. lbnMemFree(small, SMALL);
  613. #endif
  614. return 0; /* Success */
  615. }