summaryrefslogtreecommitdiff
path: root/proc/primes.c
blob: 1561cf21c729711a83c6555ec049016037fded1f (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
/* Prime number generation
   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>

/* Return the next prime greater than or equal to N. */
int 
nextprime (int n)
{
  static int *q;
  static int k = 2;
  static int l = 2;
  int p;
  int *m;
  int i, j;
  
  /* You are not expected to understand this. */

  if (!q)
    {
      /* Init */
      q = malloc (sizeof (int) * 2);
      q[0] = 2;
      q[1] = 3;
    }

  if (n <= q[0])
    return q[0];

  while (n > q[l - 1])
    {
      /* Grow */

      /* Alloc */
      p = q[l-1] * q[l-1];
      m = alloca (sizeof (int) * p);
      bzero (m, sizeof (int) * p);
      
      /* Sieve */
      for (i = 0; i < l; i++)
	for (j = q[i] * 2; j < p; j += q[i])
	  m[j] = 1;

      /* Copy */
      for (i = q[l-1] + 1; i < p; i++)
	{
	  if (l == k)
	    {
	      q = realloc (q, k * sizeof (int) * 2);
	      k *= 2;
	    }
	  if (!m[i])
	    q[l++] = i;
	}
    }
  
  /* Search */
  i = 0;
  j = l - 1;
  p = j / 2;

  while (q[p - 1] >= n || q[p] < n)
    {
      if (n > q[p])
	i = p + 1;
      else
	j = p - 1;
      p = ((j - i) / 2) + i;
    }
  
  return q[p];
}