【Print prime numbers】

Topic: Print prime numbers between 100 and 200

Prime number: That is, a prime number. In addition to 1 and itself, there are no other divisors, then the data is a prime number.

Method One: Trial Division

Defect: Data that exceeds half of i is definitely not a multiple of i. Many meaningless operations are performed above.

int main()
{
    
                                                
	int i = 0;
	int count = 0;

    // 外层循环用来获取100~200之间的所有数据,100肯定不是素数,因此i从101开始
	for(i=101; i<=200; i++)
	{
    
    
		//判断i是否为素数:用[2, i)之间的每个数据去被i除,只要有一个可以被整除,则不是素数
		int j = 0;
		for(j=2; j<i; j++)
		{
    
    
			if(i%j == 0)
			{
    
    
				break;
			}
		}
        
		// 上述循环结束之后,如果j和i相等,说明[2, i)之间的所有数据都不能被i整除,则i为素数
		if(j==i)
		{
    
    
			count++;
			printf("%d ", i);
		}
	}


	printf("\ncount = %d\n", count);
	return 0;
}

Method 2: Every time you get a piece of data, you only need to check whether there is an element in the interval [2, i/2] that can be divisible by 2i, which means that i is not a prime number.

int main()
{
    
    
	int i = 0;//
	int count = 0;
	for(i=101; i<=200; i++)
	{
    
    
		//判断i是否为素数
		//2->i-1
		int j = 0;
		for(j=2; j<=i/2; j++)
		{
    
    
			if(i%j == 0)
			{
    
    
				break;
			}
		}
		//...
		if(j>i/2)
		{
    
    
			count++;
			printf("%d ", i);
		}
	}
	printf("\ncount = %d\n", count);
	return 0;
}

Method three

/*
Method 2 still contains some repeated data, and is optimized again:
If i can be [2, sqrt(i)] If m is divisible by any integer between 2 ~ m-1, then i is not a prime number
Reason: If m can be divisible by any integer between 2 ~ m-1, one of its two factors must be less than or equal to sqrt( m), the other is greater than or equal to sqrt(m).
*/
int main()
{ int i = 0; int count = 0;

for(i=101; i<=200; i++)
{
	//判断i是否为素数
	//2->i-1
	int j = 0;
	for(j=2; j<=sqrt(i); j++)
	{
		if(i%j == 0)
		{
			break;
		}
	}
	//...
	if(j>sqrt(i))
	{
		count++;
		printf("%d ", i);
	}
}


printf("\ncount = %d\n", count);
return 0;

}

Method 4

Continue to optimize method three. As long as i is not divisible by any data between [2, sqrt(i)], then i is a prime number. However, in actual operation, i does not need to gradually increase from 101 to 200 because 2 and 3 are out of the equation. In addition, there will not be two consecutive adjacent data that are prime numbers at the same time.

int main()
{
    
    
	int i = 0;
	int count = 0;


	for(i=101; i<=200; i+=2)
	{
    
    
		//判断i是否为素数
		//2->i-1
		int j = 0;
		for(j=2; j<=sqrt(i); j++)
		{
    
    
			if(i%j == 0)
			{
    
    
				break;
			}
		}
		//...
		if(j>sqrt(i))
		{
    
    
			count++;
			printf("%d ", i);
		}
	}

	printf("\ncount = %d\n", count);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_53869058/article/details/134184635