/* SPDX-FileCopyrightText: 2021 John Scott <jscott@posteo.net>
 * SPDX-License-Identifier: GPL-3.0-or-later
 * Count the number of primes that fit into an int16_t. */
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>

static int16_t primes[4096];
static bool isprime(int16_t n) {
	const int16_t *div = primes;
	while(*div && *div < n) {
		if(!(n % *div)) {
			return false;
		}
		div++;
	}
	return true;
}

int main(void) {
	size_t count = 0;
	for(int16_t i = 2; i < INT16_MAX; i++) {
		if(isprime(i)) {
			primes[count++] = i;
			assert(count < sizeof(primes)/sizeof(*primes));
		}
	}
	/* Currently Newlib seems to not recognize the %zu format specifier. */
	if(printf("%d\n", (int)count) < 0) {
		perror("Failed to print prime count");
		abort();
	}
}
