1
0
Fork 0

Problem 35; corrected upper bound of prime-counting function in primes.c

This commit is contained in:
Jonathan Chan 2016-12-05 02:44:09 -08:00
parent b89d7b5c6f
commit d78b3827c1
3 changed files with 73 additions and 7 deletions

BIN
35 Executable file

Binary file not shown.

63
35.c Normal file
View File

@ -0,0 +1,63 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include "primes.h"
int main () {
int bound = 1000000;
int* primes;
bool* primesTable;
int numPrimes = listOfPrimes (bound, &primes, &primesTable);
bool* circularPrimesTable = calloc (bound + 1, sizeof (bool));
for (int i = 0; i < numPrimes; i++) {
if (circularPrimesTable[primes[i]] != true) {
int n = primes[i];
int numOfDigits = floor (log10 (n)) + 1;
int* digits = malloc (sizeof (int) * numOfDigits);
for (int d = 0; d < numOfDigits; d++) {
digits[d] = n % 10;
n /= 10;
}
int* circles = malloc (sizeof (int) * numOfDigits);
for (int c = 0; c < numOfDigits; c++) {
circles[c] = 0;
for (int d = c; d < c + numOfDigits; d++) {
circles[c] += digits[d % numOfDigits] * (int) pow (10, d - c);
}
}
free (digits);
bool circular = true;
for (int c = 0; c < numOfDigits; c++) {
if (primesTable[circles[c]] == false) {
circular = false;
break;
}
}
if (circular) {
for (int c = 0; c < numOfDigits; c++) {
circularPrimesTable[circles[c]] = true;
}
}
free (circles);
}
}
free (primes);
free (primesTable);
int sum = 0;
for (int i = 0; i <= bound; i++) {
if (circularPrimesTable[i]) {
sum++;
printf ("%d ", i);
}
}
free (circularPrimesTable);
printf ("\n%d\n", sum);
}

View File

@ -52,7 +52,7 @@ bool isPrimeMem (int n, int* primes) {
*
* N.B. numOfPrimesUpper is an upper-bound of
* the prime-counting function, given by
* n/ln(n) * (1 + 3/2 * 1/ln(n))
* n/ln(n) * 1.25506
*
* runs in O(n * sqrt(n)/ln(n)) (not a tight bound)
*
@ -66,19 +66,22 @@ int listOfPrimes (int n, int** primes_ptr, bool** primesTable_ptr) {
return 0;
}
int numOfPrimesUpper = (int) (n/log(n) *
(1 + 3/2 * 1/log(n)));
int numOfPrimesUpper = (int) (n/log(n) * 1.25506);
*primes_ptr = malloc (sizeof (int) * numOfPrimesUpper);
int numOfPrimes = 0;
for (int i = 0; i <= n; i++) {
if (isPrimeMem (i, *primes_ptr)) {
(*primes_ptr)[numOfPrimes++] = i;
(*primes_ptr)[numOfPrimes] = i;
(*primesTable_ptr)[i] = true;
numOfPrimes++;
}
}
if (numOfPrimes < numOfPrimesUpper)
*primes_ptr = realloc (*primes_ptr,
if (numOfPrimes < numOfPrimesUpper) {
int* tmp = realloc (*primes_ptr,
sizeof (int) * numOfPrimes);
if (tmp != NULL)
*primes_ptr = tmp;
}
return numOfPrimes;
}