Sieve method to find all prime numbers between 2~1000

Source: Internet
Author: User
Tags printf

The Sieve method to calculate the prime must first establish the sieve, here uses the array as the sieve. The subscript corresponds to the number, the corresponding subscript variable's value flag is in the sieve: for 1 in the sieve, for. The expression has been sifted out, not in the sieve. Then look for each round to filter the seed, and the seed is the next smallest prime number after a round of screening, with an initial value of 2.

Filter the seeds for each round and sift through all their multiples, that is, the value of the corresponding subscript variable is assigned to O. The initial multiples are twice times that of the filtered seeds.

The filter is complete, and the remainder of the sieve is prime.

The procedure is as follows:

/*程序8—14,筛法求2至1000之间的所有素数*/
main()
{
int a[1000];/*筛子数组*/
int i;
int minp,double;/*minp筛选种子,double倍数*/
int n=O;/*素数个数,用于输出格式控制*/
for(i=2;i<1000;i++)/*建立筛子*/

a[i]=1;
minp=2;/*筛选种子初始化*/
while(minp<500)/*完成整个筛选*/
{double=2*minp;/*倍数初始化*/
while(double<1000)/*完成一轮筛选*/
{a[double]=O;/*筛去当前倍数*/
double+=minp;/*计算下一个倍数*/
}
do/*计算下一轮筛选种子*/
{minp++;}
while(a[minp]==0);
}

printf("2至1000之间的所有素数如下:\n");
for(i=2;i<1000;i++)
if(a[i]==1)
{printf("%6d",i);
n++;
if(n%5==0)printf("\n");/*5个素数输出在一行*/
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.