eratosthenes.c 8.69 KB
Newer Older
Niels Möller's avatar
Niels Möller committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* eratosthenes.c
 *
 * An implementation of the sieve of Eratosthenes, to generate a list of primes.
 *
 */
 
/* nettle, low-level cryptographics library
 *
 * Copyright (C) 2007 Niels Mller
 *  
 * The nettle 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 2.1 of the License, or (at your
 * option) any later version.
 * 
 * The nettle 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 nettle library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
 * MA 02111-1307, USA.
 */

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

#include "getopt.h"

#ifdef SIZEOF_LONG
# define BITS_PER_LONG (CHAR_BIT * SIZEOF_LONG)
# if BITS_PER_LONG > 32
#  define NEED_HANDLE_LARGE_LONG 1
# else
#  define NEED_HANDLE_LARGE_LONG 0
# endif
#else
# define BITS_PER_LONG (CHAR_BIT * sizeof(unsigned long))
# define NEED_HANDLE_LARGE_LONG 1
#endif


static void
usage(void)
{
  fprintf(stderr, "Usage: erathostenes [OPTIONS] [LIMIT]\n\n"
	  "Options:\n"
	  "      --help         Display this message.\n"
56
	  "      --quiet        No summary line.\n"
Niels Möller's avatar
Niels Möller committed
57
58
59
60
	  "      --odd-only     Omit the prime 2.\n"
	  "      --primes-only  Suppress output of differences.\n"
	  "      --diff-only    Supress output of primes.\n"
	  "      --tabular      Tabular output (default is one prime per line).\n"
61
	  "      --block SIZE   Block size.\n");
Niels Möller's avatar
Niels Möller committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
}

static unsigned
isqrt(unsigned n)
{
  unsigned x;

  /* FIXME: Better initialization. */
  if (n < UINT_MAX)
    x = n;
  else
    /* Must avoid overflow in the first step. */
    x = n-1;  

  for (;;)
    {
      unsigned y = (x + n/x) / 2;
      if (y >= x)
	return x;

      x = y;
    }
}

/* Size is in bits */
static unsigned long *
vector_alloc(unsigned size)
{
  unsigned end = (size + BITS_PER_LONG - 1) / BITS_PER_LONG;
  unsigned i;
  unsigned long *vector = malloc (end * sizeof(long));
  
  if (!vector)
    return NULL;

  for (i = 0; i < end; i++)
    vector[i] = ~0;

  return vector;
}

static void
vector_clear_bits (unsigned long *vector, unsigned step, unsigned start, unsigned size)
{
106
  unsigned bit;
Niels Möller's avatar
Niels Möller committed
107

108
  for (bit = start; bit < size; bit += step)
Niels Möller's avatar
Niels Möller committed
109
    {
110
111
      unsigned i = bit / BITS_PER_LONG;
      unsigned long mask = 1L << (bit % BITS_PER_LONG);
Niels Möller's avatar
Niels Möller committed
112

113
      vector[i] &= ~mask;
Niels Möller's avatar
Niels Möller committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
    }
}

static unsigned
find_first_one (unsigned long x)
{
  unsigned table[0x10] =
    {
      /* 0, 1,  2,  3,  4,  5,  6,  7 */
        -1, 0,  1,  0,  2,  0,  1 , 0,
      /* 8, 9, 10, 11, 12, 13, 14, 15 */
	 3, 0,  1,  0,  2,  0,  1,  0
    };

  /* Isolate least significant bit */
  x &= -x;
  
  unsigned i = 0;
#if NEED_HANDLE_LARGE_LONG
#ifndef SIZEOF_LONG
  /* Can't not be tested by the preprocessor. May generate warnings
     when long is 32 bits. */
  if (BITS_PER_LONG > 32)
#endif
    while (x >= 0x100000000L)
      {
	x >>= 32;
	i += 32;
      }
#endif /* NEED_HANDLE_LARGE_LONG */

  if (x >= 0x10000)
    {
      x >>= 16;
      i =+ 16;
    }
  if (x >= 0x100)
    {
      x >>= 8;
      i += 8;
    }
  if (x >= 0x10)
    {
      x >>= 4;
      i += 4;
    }
  return i + table[x & 0xf];
}

/* Returns size if there's no more bits set */
static unsigned
vector_find_next (const unsigned long *vector, unsigned bit, unsigned size)
{
  unsigned end = (size + BITS_PER_LONG - 1) / BITS_PER_LONG;
  unsigned i = bit / BITS_PER_LONG;
  unsigned long mask = 1L << (bit % BITS_PER_LONG);
  unsigned long word;

  if (i >= end)
    return size;

  for (word = vector[i] & ~(mask - 1); !word; word = vector[i])
    if (++i >= end)
      return size;

  /* Next bit is the least significant bit of word */
  return i * BITS_PER_LONG + find_first_one(word);
}

struct output_info
{
  int output_2;
  enum {
187
    FORMAT_PRIMES = 1, FORMAT_DIFF = 2, FORMAT_TABULAR = 4
Niels Möller's avatar
Niels Möller committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
  } format;

  unsigned long last;
  unsigned column;
};

static void
output_init(struct output_info *info)
{
  info->output_2 = 1;
  info->format = FORMAT_PRIMES | FORMAT_DIFF;
  info->last = 0;
}

static void
output(struct output_info *info, unsigned long p)
{
205
  if (info->format & (FORMAT_PRIMES | FORMAT_DIFF))
Niels Möller's avatar
Niels Möller committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
    {
      if (info->format & FORMAT_PRIMES)
	printf("%ld", p);
      if (info->format & FORMAT_DIFF)
	printf(" %ld", p - info->last);

      if (info->format & FORMAT_TABULAR)
	{
	  printf(",");
	  info->column++;
	  if (info->column == 16)
	    {
	      printf("\n");
	      info->column = 0;
	    }
	  else
	    printf(" ");
	}
      else
	printf("\n");
    }
  info->last = p;
}

static void
output_first(struct output_info *info)
{
233
234
235
  info->column = 0;
  if (info->output_2)
    output(info, 2);
Niels Möller's avatar
Niels Möller committed
236

237
  info->last = 2;
Niels Möller's avatar
Niels Möller committed
238
239
240
241
242
243
244
245
246
247
248
249
}

int
main (int argc, char **argv)
{
  unsigned long *vector;
  /* Generate all primes p <= limit */
  unsigned limit;
  unsigned size;
  unsigned bit;
  unsigned prime_count;
  unsigned sieve_limit;
250
251
  unsigned block_size;
  unsigned block;
Niels Möller's avatar
Niels Möller committed
252
253
254
255
256

  struct output_info info;
  int quiet;
  int c;
  
257
  enum { FLAG_ODD = -100, FLAG_PRIME, FLAG_DIFF, FLAG_TABULAR,
258
	 FLAG_QUIET, FLAG_BLOCK };
Niels Möller's avatar
Niels Möller committed
259
260
261
262
263
  
  static const struct option options[] =
    {
      /* Name, args, flag, val */
      { "help", no_argument, NULL, '?' },
264
      { "quiet", no_argument, NULL, FLAG_QUIET },
Niels Möller's avatar
Niels Möller committed
265
266
267
268
      { "odd-only", no_argument, NULL, FLAG_ODD },
      { "prime-only", no_argument, NULL, FLAG_PRIME },
      { "diff-only", no_argument, NULL, FLAG_DIFF },
      { "tabular", no_argument, NULL, FLAG_TABULAR },
269
      { "block" , required_argument, NULL, FLAG_BLOCK },
Niels Möller's avatar
Niels Möller committed
270
271
272
273
274
      { NULL, 0, NULL, 0}
    };

  output_init(&info);

275
276
277
  quiet = 0;
  block_size = 0;
  
Niels Möller's avatar
Niels Möller committed
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
  while ( (c = getopt_long(argc, argv, "?", options, NULL)) != -1)
    switch (c)
      {
      case '?':
	usage();
	return EXIT_FAILURE;
      case FLAG_ODD:
	info.output_2 = 0;
	break;
      case FLAG_PRIME:
	info.format &= ~FORMAT_DIFF;
	break;
      case FLAG_DIFF:
	info.format &= ~FORMAT_PRIMES;
	break;
      case FLAG_TABULAR:
	info.format |= FORMAT_TABULAR;
	break;
      case FLAG_QUIET:
	quiet = 1;
	break;
299
300
301
302
303
304
305
306
307
308
309
      case FLAG_BLOCK:
	{
	  int arg = atoi(optarg);
	  if (arg <= 10)
	    {
	      usage();
	      return EXIT_FAILURE;
	    }
	  block_size = (arg - 3) / 2;
	  break;
	}
Niels Möller's avatar
Niels Möller committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
      default:
	abort();
      }

  argc -= optind;
  argv += optind;

  if (argc == 0)
    limit = 1000;
  else if (argc == 1)
    {
      limit = atoi(argv[0]);
      if (limit < 2)
	return EXIT_SUCCESS;
    }
  else
    {
      usage();
      return EXIT_FAILURE;
    }

  size = (limit - 1) / 2;

333
334
335
  if (!block_size || block_size > size)
    block_size = size;

Niels Möller's avatar
Niels Möller committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
  vector = vector_alloc (size);
  if (!vector)
    {
      fprintf(stderr, "Insufficient memory.\n");
      return EXIT_FAILURE;
    }

  output_first(&info);
  prime_count = 1;

  bit = 0;

  if (limit == 2)
    return EXIT_SUCCESS;

351
  sieve_limit = (isqrt(2*block_size + 1) - 1) / 2;
Niels Möller's avatar
Niels Möller committed
352
353
354
355
356
357
358
359
360
361
362
363
  
  while (bit < sieve_limit)
    {
      unsigned n = 3 + 2 * bit;
      
      output(&info, n);
      prime_count++;

      /* First bit to clear corresponds to n^2, which is bit

	 (n^2 - 3) / 2 = n * bit + 3 (bit + 1)
      */
364
      vector_clear_bits (vector, n, n*bit + 3*(bit + 1), block_size);
Niels Möller's avatar
Niels Möller committed
365

366
      bit = vector_find_next (vector, bit + 1, block_size);
Niels Möller's avatar
Niels Möller committed
367
368
369
    }

  /* No more marking, just output the remaining primes. */
370
  while (bit < block_size)
Niels Möller's avatar
Niels Möller committed
371
    {
372
      output(&info, 3 + 2 * bit);
Niels Möller's avatar
Niels Möller committed
373
374
375
376
377
      prime_count++;

      bit = vector_find_next (vector, bit + 1, size);
    }

378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
  for (block = block_size; block < size; block += block_size)
    {
      unsigned block_start;
      unsigned block_end;

      if (block + block_size > size)
	/* For the final block */
	block_size = size - block;

      block_start = 2*block + 3;
      block_end = 2*(block + block_size) + 3;

      sieve_limit = (isqrt(block_end) - 1) / 2;
      for (bit = 0; bit < sieve_limit ;)
	{
	  unsigned n = 3 + 2 * bit;

	  unsigned start = n*bit + 3*(bit + 1);
	  if (start < block)
	    {
	      unsigned k = (block + 1) / n;
	      start = bit + k*n;
	    }
	  vector_clear_bits (vector, n, start, block + block_size);
	  
	  bit = vector_find_next (vector, bit + 1, block + block_size);
	}
      for (bit = vector_find_next (vector, block, block + block_size);
	   bit < block + block_size;
	   bit = vector_find_next (vector, bit + 1, block + block_size))
	{
	  output(&info, 3 + 2 * bit);
	  prime_count++;
	}
    }

Niels Möller's avatar
Niels Möller committed
414
415
416
417
418
419
420
421
  if (!quiet)
    {
      printf("\n");
      fprintf(stderr, "Prime #%d = %ld\n", prime_count, info.last);
    }

  return EXIT_SUCCESS;
}