菜鸟编程练习生之<素数的输出>循环与条件语句
作者:互联网
int main()
{
int a = 0;
int count = 0;
for (a = 100;a <= 200;a++)
{
int j = 0;
for (j = 2;j < a;j++)
{
if (a % j == 0)
{
break;
}
}
if (j == a)
{
count++;
printf("%d ", a);
}
}
printf("\ncount = %d\n", count);
return 0;
}
优化后
int main()
{
int a = 0;
int count = 0;
for (a = 100;a <= 200;a++) for (a = 101;a <= 20 ;a+=2) //偶数绝对不是素数,排除偶数在奇数里面选又可以减少运算
{
int j = 0;
for (j = 2;j < sqrt(a);j++) //用开平方代替a 减少运算
{
if (a % j == 0)
{
break;
}
}
if (j > sqrt(a)) 其实,也可以把开方换成a/2,那么下面就是if(j==a/2)也可以达到目的
{
count++;
printf("%d ", a);
}
}
printf("\ncount = %d\n", count);
标签:count,练习生,int,菜鸟,编程,ncount,sqrt,++,printf 来源: https://www.cnblogs.com/SGZY1/p/15496650.html