]> git.ozlabs.org Git - ccan/blob - ccan/eratosthenes/test/run.c
io/fdpass: fix example.
[ccan] / ccan / eratosthenes / test / run.c
1 #include <ccan/eratosthenes/eratosthenes.h>
2 #include <ccan/tap/tap.h>
3
4 #include <ccan/eratosthenes/eratosthenes.c>
5
6 #define LIMIT   500
7
8 #define ok_eq(a, b) \
9         ok((a) == (b), "%s [%u] == %s [%u]", \
10            #a, (unsigned)(a), #b, (unsigned)(b))
11
12 static bool test_isprime(unsigned long n)
13 {
14         int i;
15
16         if (n < 2)
17                 return false;
18
19         for (i = 2; i < n; i++)
20                 if ((n % i) == 0)
21                         return false;
22
23         return true;
24 }
25
26 static unsigned long test_nextprime(struct eratosthenes *s, unsigned long n)
27 {
28         unsigned long i = n + 1;
29
30         while ((i < LIMIT) && !eratosthenes_isprime(s, i))
31                 i++;
32
33         return (i >= LIMIT) ? 0 : i;
34 }
35
36 int main(void)
37 {
38         struct eratosthenes s;
39         unsigned long n;
40
41         /* This is how many tests you plan to run */
42         plan_tests(2 * LIMIT);
43
44         eratosthenes_init(&s);
45
46         eratosthenes_sieve(&s, LIMIT);
47
48         for (n = 0; n < LIMIT; n++) {
49                 ok_eq(eratosthenes_isprime(&s, n), test_isprime(n));
50                 ok_eq(eratosthenes_nextprime(&s, n), test_nextprime(&s, n));
51         }
52
53         eratosthenes_reset(&s);
54
55         /* This exits depending on whether all tests passed */
56         return exit_status();
57 }