C语言求素数(质数)Eratosthenes经典算法
// 使用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;
}
本文档为【C语言求素数(质数)Eratosthenes经典算法】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。