如果您试图找出不超过给定数字(在您的情况下为 2..100)的素数,则构建素数表将加快该过程:
注意:输入是连续的以帮助构建素数表,这一点很重要。
#include <stdio.h>
#include <math.h>
/* Building a prime table for fast look up
* NOTE : Numbers should be input from 2 to n in a sequential pattern to help build prime table; */
# define PRIME_TAB_MAX 200
int prime_specific(int num)
{
static int primeTab[PRIME_TAB_MAX] = { 0, };
static int primeCount = 0;
int check_limit ;
unsigned int idx;
if (num < 2)
return 0;
if (primeCount > 0) {
check_limit = (int)sqrt(num);
for (idx = 0; idx < primeCount && primeTab[idx] <= check_limit; idx++) {
if (0 == (num % primeTab[idx])) {
return 0;
}
}
}
else {
for (idx = 2; idx <= num / 2; idx++)
if (0 == (num % idx))
return 0;
}
if (primeCount < PRIME_TAB_MAX) {
primeTab[primeCount++] = num;
return 1;
}
else {
fprintf(stderr, "\nERROR: Prime Table is full");
return (-1); //Internal error
}
}
int main(void)
{
unsigned int idx;
int status ;
for (idx = 2; idx <= 1000; idx++) {
status = prime_specific(idx);
switch (status)
{
case 1:
fprintf(stderr, "%d\n", idx);
break;
case 0:
//Do nothing
break;
default:
fprintf(stderr, "\nERROR:Internal Error");
return (-1);
}
}
return 0;
}