求100到1000之间的素数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40567865/article/details/82988298

环境:win10 vs2017

方法一

#include<stdio.h>
#include<windows.h>
int main()
{
	int i = 0;
	int count = 0;//计算素数的个数
	for (i = 100; i <= 1000; i++)
	{
		int j = 0;
		for (j = 2; j <i; j++)
		{
			if (i%j == 0)
			{
				break;
			}
		}
		if (j >= i )
		{
			count++;//计算素数的个数
			printf("%d ", i);
		}
	}
	printf("%d", count);
	system("pause");
	return 0;
}

方法二

#include<stdio.h>
#include<windows.h>
int main()
{
	int i = 0;
	int count = 0;
	for (i = 100; i <= 1000; i++)
	{
		int j = 0;
		for (j = 2; j <= i / 2; j++)//当一个数不能被它的一半以前的数字整除时,那么它就是素数
		{
			if (i%j == 0)
			{
				break;
			}
		}
		if (j > i / 2)//j大于i/2时,表示上述所有数字都不被它整除,那么它就是素数
		{
			count++;
			printf("%d ", i);
		}
	}
	printf("%d", count);
	system("pause");
	return 0;
}

方法三

#include<stdio.h>
#include<windows.h>
#include <math.h>
int main()
{
	int i = 0;
	int count = 0;
	for (i = 100; i <= 1000; i++)
	{
		int j = 0;
		for (j = 2; j <=sqrt(i); j++)//一个数不能被它的平方根以前的数字整除时,那么它就是素数
		{
			if (i%j == 0)
			{
				break;
			}
		}
		if (j >sqrt(i) )
		{
			count++;
			printf("%d ", i);
		}
	}
	printf("%d", count);
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40567865/article/details/82988298