Sunday, April 20, 2008 - 2:19 pm

Source Code: Generating the First 1001 Primes

I did not intend to post the source code here. But oh well, here's the obfuscated code that generated the list of prime numbers in the previous post.
/* Generates a file containing the first 10001 prime numbers */

#include ‹stdio.h›

int main()
{
#define TRUE 1
#define FALSE 0
#define MAX 10001-1
void saveresult(int result[MAX]);

int x,
y=0,
i=0,
retrieve;
int prime[MAX]; /* Tracks all known primes */
int boolean;

prime[0] = 2;

for (x=3; y‹MAX; x+=2) /* Check only odd numbers */
{
boolean=TRUE; /* All numbers are presumed to be primes until proven otherwise */

for (i=0; i‹y; i++) /* Check if y is a factor of x */
{
if (x%prime[i] == 0) /* x is a multiple of y */
{
boolean = FALSE;
break; /* x is not a prime; stop the loop */
}
}

if (boolean == TRUE)
{
prime[i+1] = x; /* Add new prime to array */
//printf("%d\t", prime[i+1]); /* Print newly added prime */
y++;
}

}

///////////////////////////////////
/* Prompt the user for which prime number to retrieve */
printf("First 10001 prime numbers generated.\n");
for ( ; ; )
{
do
{
printf("Which one to retrieve?");
scanf("%d", &retrieve);
}while (retrieve‹1 || retrieve › MAX+1);

printf("The %d-th prime number is: %d\n\n", retrieve, prime[retrieve-1]);
}

saveresult(prime);

return 0;
}

void saveresult(int result[MAX])
{
FILE *fp_write;
int n;

fp_write = fopen("primeNbrRslt.txt", "w");

for (n=0; n‹MAX; n++)
{
fprintf(fp_write, "%d ", result[n]);
}

fclose(fp_write);
}

No comments: