summaryrefslogtreecommitdiff
path: root/proc/primes.c
blob: 1071e116b930922d31e51aab8e66de2bd2bdeec0 (plain)
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
56
57
58
59
60
61
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
/* Seive of Eratosthenes
   Copyright (C) 1994 Free Software Foundation

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

   This program 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
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */

#include <stdlib.h>
#include <string.h>

/* Array of prime numbers */
int *primes;

/* Allocated size of array `primes'. */
int primessize;

/* Number of primes recorded in array `primes'. */
int nprimes;

/* Initialize primes  */
void
initprimes ()
{
  primessize = 2;
  nprimes = 2;
  primes = malloc (sizeof (int) * 2);
  primes[0] = 2;
  primes[1] = 3;
}

/* Return the next prime greater than or equal to n. */
int 
nextprime (int n)
{
  int p;
  int low, high;
  int *iscomp;
  int nints;
  int lastprime = primes[nprimes - 1];
  int i, j;
  
  if (n < primes[0])
    return primes[0];

  while (n > primes[nprimes - 1])
    {
      nints = lastprime * lastprime;
      iscomp = alloca (sizeof (int) * nints);
      bzero (iscomp, sizeof (int) * nints);
      
      for (i = 0; i < nprimes; i++)
	for (j = primes[i] * 2; j < nints; j += primes[i])
	  iscomp[j] = 1;

      for (i = lastprime; i < nints; i++)
	{
	  if (nprimes == primessize)
	    {
	      primes = realloc (primes, primessize * sizeof (int) * 2);
	      primessize *= 2;
	    }
	  if (!iscomp[i])
	    primes[nprimes++] = i;
	}
    }
  
  /* Binary search */
  low = 0;
  high = nprimes - 1;
  p = high / 2;

  /* This works because nprimes is always at least 2. */
  while (primes[p - 1] >= n || primes[p] < n)
    {
      if (n > primes[p])
	low = p;
      else
	high = p;
      p = ((high - low) / 2) + low;
    }
  
  return primes[p];
}


main ()
{
  int i;

  initprimes();
  
  for (i = 0; i < 100; i++)
    printf ("%d\t%d\n", i, nextprime(i));
}