C语言求素数(质数)Eratosthenes经典算法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
//使用Eratosthenes方法找出指定范围内的所有质数
#include
#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; }