Prime table at translate time
The compiler sieves the primes below 60 and emits a constant array and a count.
+ <stdio.h>
# A lookup table computed by the compiler: @tt sieves the primes below 60 and emits a constant array.
@tt
found:=[]
names:=[]
for n 2..60
prime:=true
for p found
if n % p == 0
prime = false
if prime
found = push(found, n)
names = push(names, str(n))
emit("static const int primes[] = {" + join(names, ", ") + "};")
emit("enum { PRIME_COUNT = " + str(len(found)) + " };")
f main()
printf("%d primes below 60:", PRIME_COUNT)
for i := 0; i < PRIME_COUNT; i++
printf(" %d", primes[i])
printf("\n")
< 0
#include <stdio.h>
static const int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59};
enum {
PRIME_COUNT = 17
};
int main(void) {
printf("%d primes below 60:", PRIME_COUNT);
for (int i = 0; i < PRIME_COUNT; i++) {
printf(" %d", primes[i]);
}
printf("\n");
return 0;
}
Output
17 primes below 60: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59
What it shows
@tt, lists, emit