aboutsummaryrefslogtreecommitdiff
path: root/challenge-198/duncan-c-white/C/primes.c
blob: 9e9d0ba0fb686f8fee838e859b2b9bf953787e13 (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
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>


// int *primes = primes_upto(n,&numprimes);
//	Generate a dynamic array of integers containing
//	all primes up to $n.  The array is zero-terminated.
//	We also set numprimes to the number of primes found.
//	The caller should free(primes) when they've finished
//	using it.
//
int * primes_upto( int n, int *numprimep )
{
	bool *isprime = (bool *) malloc( (n+1) * sizeof(bool) );
	assert( isprime != NULL );

	int i;
	for( i=1; i<=n; i++ )
	{
		isprime[i] = 1;		// initially
	}

	int upper = (int)(sqrt((double)(n)));
	//printf( "debug: n=%d, upper=%d\n", n, upper );
	for( i=2; i<=upper; i++ )
	{
		if( isprime[i] )
		{
			//printf( "debug: crossing out multiples of %d\n", i );
			int j;
			for( j=i*i; j<=n; j+=i )
			{
				isprime[j] = 0;
			}
		}
	}

	// count how many primes there are
	int np = 0;
	for( i=2; i<=n; i++ )
	{
		if( isprime[i] )
		{
			np++;
		}
	}
	*numprimep = np;

	// dynamically allocate an array of np+1 ints, and fill it in
	int *primes = malloc( (np+1) * sizeof(int) );
	int p = 0;
	for( i=2; i<=n; i++ )
	{
		if( isprime[i] )
		{
			primes[p++] = i;
		}
	}
	primes[p] = 0;

	free( isprime );

	return primes;
}