当前位置:文档之家› C语言求素数(质数)Eratosthenes经典算法

C语言求素数(质数)Eratosthenes经典算法

//使用Eratosthenes方法找出指定范围内的所有质数
#include <stdlib.h>
#define SIZE 500 //该方法能够求出2*SIZE 之内的质数#define TRUE 1
#define FALSE 0
int
main()
{
char sieve[ SIZE ]; /* the sieve */
char *sp; /* pointer to access the sieve */
int number; /* number we’re computing */
/*
** 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. (Note: the
** loop is terminated from inside.)
*/
for( number = 3; ; number += 2 ){
/*
** Set the pointer to the proper element in the sieve, and stop
** the loop if we’ve gone too far.
*/
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\t" );
for( number = 3, sp = &sieve[ 0 ];
sp<&sieve[ SIZE ];
number += 2, sp++ ){
if( *sp )
printf( "%d\t", number );
}
system("pause");
return EXIT_SUCCESS; }。

相关主题