C language: output prime numbers within 100

Topic: Output the prime numbers up to 100

Background: A prime number is a natural number greater than 1 that has no other factors except 1 and itself .

Idea: Use two for loops, one to traverse the number within 100, and one to judge the prime number, using the square root form (sqrt).

code:

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

int main()
{
	int i = 0;
	int j = 0;
	for (i = 2; i <= 100; i++)
	{
		float a = sqrt(i);//取i的开方,因为i的公因数一个小于i的开方,一个大于i的开方,还有相等的情况
		for (j = 2; j <= a; j++)//把j与i的开方作比较,减少运算
		{
			if (i % j == 0)//判断i取余j是否等于0;如果等于0则必不为素数
			{
				break;
			}
		}
		if (j > a)//如果j>a则在小于等于a的范围内没有i的公因数,此数为素数
		{
			printf("%d ", i);
		}
	}
	return 0;
}

Details: When i % j == 0 to jump out of the loop.

 

Guess you like

Origin blog.csdn.net/AAlykk/article/details/130717845