summaryrefslogtreecommitdiff
path: root/primegen.c
blob: 045c2e51d847125ebd30cad0bcf822b050d20a3b (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
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv)
{
    int opt;
    const char *optstr = "n:";
    long count = -1;
    int current, i, primecount = 0;

    while ((opt = getopt(argc, argv, optstr)) != -1)
    {
        switch (opt)
        {
        case 'n':
            count = strtol(optarg, NULL, 0);
            break;

        case '?':
            exit(1);
        }
    }

    if (count <= 0)
    {
        exit(1);
    }

    char *sieve = malloc(sizeof(char) * count);
    memset(sieve, 1, sizeof(char) * count);

    current = 2;

    while (current < count)
    {
        if (sieve[current])
        {
            primecount++;

            for (i = current*2; i < count; i+=current)
            {
                sieve[i] = 0;
            }
        }

        current++;
    }

    printf("const long prime_table[%d] = { 2", primecount);

    for (i = 3; i < count; ++i)
    {
        if (sieve[i])
        {
            printf(",%d", i);
        }
    }

    printf("\n};\n");

    printf("const long prime_table_size = %d;\n", primecount);

    free(sieve);

    return 0;
}