Eratosthenes 篩選法 c語言 陣列+指標實現
#include<stdlib.h>
#include<stdio.h>
#define SIZE 1000
#define TRUE 1
#define FALSE 0
int main()
{
char sieve[ SIZE ];
char *sp;
int number;
/*
Set the entire sieve to TRUE
*/
for( sp = sieve; sp < &sieve[ SIZE ]; )
*sp++ = TRUE;
/*
process each number from 3 to as many as the sieve holds
*/
for( number =3; ;number +=2 ){
sp = &sieve[ 0 ] + ( number -3 )/2;
if( sp >= &sieve[ SIZE ] )
break;
/*
Now advance the pointer by multiples of the number and set each subsequent entry FALSE.
*/
while( sp += number, sp < &sieve[ SIZE ] )
*sp = FALSE;
}
/* Go through the entire sieve now and print the numbers corresponding to the locations that remain TRUE */
printf( "2/n" );
for( number =3,sp = &sieve[ 0 ];sp < &sieve[ SIZE ]; number += 2 ,sp++ ){
if( *sp )
printf( "%d/n",number );
}
return EXIT_SUCCESS;
}