Four ways to print prime numbers

Definition of prime number:

Prime number: A prime number that has no divisors except 1 and itself.

Code:

Method 1: Trial division: Determine whether i is a prime number: Use every data between [2, i) to be divided by i. As long as one of them can be divided evenly, it is not a prime number.

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 two: Optimize method one. Every time you get a piece of data, you only need to get the data in the [2, i/2] interval, because the other half of the data can be obtained by multiplying the first half of the data by 2.

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 3: Optimize again. If i can be divisible by any data between [2, sqrt(i)], then i is not a prime number. Reason: If m can be divisible by any integer between
2 ~ m-1, its One of the two factors must be less than or equal to sqrt(m), and the other must be 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: In fact, i does not need to gradually increase from 101 to 200 during operation, because except for 2 and 3, 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/2301_77868664/article/details/131768184