Prime screening method (ordinary sieve and linear sieve) __ algorithm

Source: Internet
Author: User

Title: Given an n, find all prime numbers of 1~n.

Here are two methods for selecting prime numbers:

The first type: ordinary Sieve method.

Time complexity is O (Nloglogn), and the disadvantage is that a composite number may be filtered multiple times.

Code:

void Prime ()
{
	memset (tag,0,sizeof (tag));
	Tag[0]=tag[1]=1;
	for (int i=2; i*i <= N; i++)
		if (tag[i]==0) {
			prime[ct++]=i;
			for (int j=i+i;j<=n;j+=i)
				tag[j]=1
		}
}

The second type: linear sieve.

The time complexity is O (n), because each composite is guaranteed to be filtered only by its smallest mass factor. The key code in the 10th, 11 lines, because if I can complete out of prime[j], then I must be a composite, and I have the quality factor is certainly less than prime[j], so this can stop, because the back of the prime[] than I small of that quality factor to be larger.

Code:

void Prime () {
	memset (tag,0,sizeof (tag));
	int cnt=0;
	Tag[0]=tag[1]=1;
	for (int i = 2; i<n; i++) {
		if (!tag[i])
			prime[cnt++]=i;
		for (int j=0;j<cnt && prime[j]*i<n; j + +) {
			Tag[i*prime[j]] = 1;
			if (i% prime[j]==0) break;}}





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.