goldbach-conjecture/prime_sieves.c
Kyle Stevenson 222707a2b9 improved sieve
2025-02-01 14:02:00 +00:00

154 lines
No EOL
4.8 KiB
C

//
// Created by Kyle Stevenson on 01/02/2025.
//
#include "prime_sieves.h"
/**
* @brief Save a prime number to an SQLite database.
*
* @param db Pointer to the SQLite database connection.
* @param prime The prime number to save.
* @return 0 on success, or an error code on failure.
*/
int savePrimeToDatabase(sqlite3 *db, size_t prime) {
char sql[128];
snprintf(sql, sizeof(sql), "INSERT INTO primes (prime) VALUES (%zu);", prime);
char *errMsg = NULL;
int rc = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", errMsg);
sqlite3_free(errMsg);
return rc;
}
return 0;
}
/**
* @brief Create the SQLite database and table if they do not exist.
*
* @param dbFile The name of the SQLite database file.
* @return Pointer to the SQLite database connection, or NULL on failure.
*/
sqlite3* initializeDatabase(const char *dbFile) {
sqlite3 *db;
int rc = sqlite3_open(dbFile, &db);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
return NULL;
}
const char *sql = "CREATE TABLE IF NOT EXISTS primes (id INTEGER PRIMARY KEY, prime INTEGER NOT NULL);";
char *errMsg = NULL;
rc = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", errMsg);
sqlite3_free(errMsg);
sqlite3_close(db);
return NULL;
}
return db;
}
/**
* @brief Prints a progress bar to the console.
*
* @param progress The progress percentage (0-100).
*/
void printProgress(double progress) {
int barWidth = 50; // Width of the progress bar
printf("\r[");
int pos = (int)(barWidth * progress / 100.0);
for (int i = 0; i < barWidth; ++i) {
if (i < pos) printf("=");
else if (i == pos) printf(">");
else printf(" ");
}
printf("] %.2f%%", progress);
fflush(stdout); // Ensure it prints in real-time
}
void sieveOfEratosthenes(const size_t maxBits, const char *dbFile) {
// Define block size in bits (125MB = 1 billion bits)
const size_t BLOCK_SIZE_BITS = 1000000000; // 1 billion bits (125MB)
const size_t BLOCK_SIZE_BYTES = BLOCK_SIZE_BITS / 8; // Convert to bytes
// Step 1: Create database connection
sqlite3 *db = initializeDatabase(dbFile);
if (!db) {
return;
}
printf("Processing Sieve of Eratosthenes in blocks of %zu bits...\n", BLOCK_SIZE_BITS);
// Step 2: Process in 125MB blocks
size_t totalPrimes = 0;
for (size_t blockStart = 0; blockStart < maxBits; blockStart += BLOCK_SIZE_BITS) {
// Step 2a: Allocate memory for this block
uint8_t *isPrime = (uint8_t *) malloc(BLOCK_SIZE_BYTES);
if (!isPrime) {
fprintf(stderr, "Memory allocation failed for block starting at %zu!\n", blockStart);
break;
}
memset(isPrime, 0xFF, BLOCK_SIZE_BYTES); // Assume all numbers are prime
// Step 2b: Mark 0 and 1 as non-prime in the first block
if (blockStart == 0) {
clearBit(isPrime, 0);
clearBit(isPrime, 1);
}
// Step 2c: Perform Sieve of Eratosthenes **for this block**
size_t blockEnd = blockStart + BLOCK_SIZE_BITS;
if (blockEnd > maxBits) blockEnd = maxBits; // Ensure we don't exceed `maxBits`
for (size_t p = 2; p * p < blockEnd; p++) {
if (checkBit(isPrime, p - blockStart)) { // Only consider primes within this block
for (size_t j = p * p; j < blockEnd; j += p) {
clearBit(isPrime, j - blockStart);
}
}
// Print progress every 1%
if (p % (BLOCK_SIZE_BITS / 100) == 0) {
printProgress((double)p / (blockEnd - blockStart) * 100);
}
}
printf("\nSaving primes from block %zu - %zu to database...\n", blockStart, blockEnd);
// Step 2d: Save primes from this block to the database
for (size_t i = 0; i < BLOCK_SIZE_BITS && (blockStart + i) < maxBits; i++) {
if (checkBit(isPrime, i)) {
size_t prime = blockStart + i;
if (savePrimeToDatabase(db, prime) != 0) {
fprintf(stderr, "Failed to save prime: %zu\n", prime);
break;
}
totalPrimes++;
// Print progress every 100,000 primes saved
if (totalPrimes % 100000 == 0) {
printf("\rSaved %zu primes...", totalPrimes);
fflush(stdout);
}
}
}
// Step 2e: Free memory before processing next block
free(isPrime);
}
printf("\nTotal primes found: %zu\n", totalPrimes);
printf("Primes saved to the database.\n");
// Step 3: Cleanup
sqlite3_close(db);
}