[Erradhotheus sieve] C language implementation of prime numbers

1. Algorithm Introduction

Eratosthenes Sieve is a method for finding prime numbers, proposed by the ancient Greek mathematician Eratosthenes.

2. Algorithm process

(1) Read the input integer n, and record all integers from 2 to n in the table;
(2) Starting from 2, cross out all multiples of 2 in the table;
(3) Find the next one in the table from small to large For an integer that has not been crossed out, then cross out all the multiples of the integer in the table;
(4) Repeat step (3) until the found integer is greater than the root sign n ;
(5) All the integers that have not been crossed out in the table are prime numbers.
The flow chart of the Eratosthenes sieve algorithm is shown in the figure below:
insert image description here

3. C language code

# include <stdio.h>
# include <math.h>

int flags[10010] = {
    
     0 };   // 0代表质数,1代表合数 
int isprime[10010] = {
    
     0 }; // 质数的集合 
int i, j;
int num;                    // [2,N]中质数的个数

void getprimes(unsigned long long N);

int main()
{
    
    
	unsigned long long N;
	
	printf("请输入N: ");
	scanf("%lld", &N);
	getprimes(N);
	
	return 0;
}

void getprimes(unsigned long long N)
{
    
    
	for(i = 2;i < sqrt(N) + 1;i ++)
	{
    
    
		if(flags[i] == 0)
		{
    
    
			j =  i * i; //从i的平方开始标记 
			while(j <= N)
			{
    
    
				//将所有i的倍数(除i本身之外)标记为合数
				flags[j] = 1; 
				j += i;
			}
		}
	}
	
	printf("[2,N]中的全部质数为:\n");
	
	for(i = 2;i <= N;i ++)
	{
    
    
		if(flags[i] == 0) //若i为质数
		{
    
    
			num ++; 
			printf("%d ", i);
		}
	}
	
	printf("\n");
	printf("共 %lld 个", num); 
}

Code explanation: For simplicity of the code, the function does not look for the "next" integer that has not been crossed out, but directly increments i by 1, resulting in some unnecessary judgments.

4. Test cases

Find all prime numbers from 2 to 150:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_43031313/article/details/130308419