1. 打印100~200 之间的素数
(1)让它依次试除“2~比自身小1的数”
素数:指只能被1和它本身整除的数。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int i = 0;
int count = 0;
for (i = 100; i <= 200; i++)
{
int j = 0;
for (j = 2; j < i; j++)
{
if (i%j == 0)
{
break;
}
}
if (i == j)
{
printf("%d ", i);
count++;
}
}
printf("\n%d\n", count);
system("pause");
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/4fef6441cd337ad5ba66b0976ba0f3e8.png)
(2)优化:
优化1:
int main()
{
int i = 0;
int j = 0;
int count = 0;
for (i = 100; i < 200; i++)
{
for (j = 2; j <=(i/2); j++)
{
if (i%j == 0)
break;
}
if (j>(i/2))
{
printf("%d ", i);
count++;
}
}
printf("count=%d\n", count);
system("pause");
return 0;
}
优化2:
int main()
{
int i = 0;
int j = 0;
int count = 0;
for (i = 101; i < 200; i+=2)
{
for (j = 2; j < i; j++)
{
if (i%j == 0)
break;
}
if (i == j)
{
printf("%d ", i);
count++;
}
}
printf("count=%d\n", count);
system("pause");
return 0;
}
优化3:
# define _CRT_SECURE_NO_WARNINGS 1
# include<stdio.h>
# include<math.h>
int main()
{
int i = 0;
int j = 0;
int count = 0;
for (i = 100; i < 200; i++)
{
for (j = 2; j <= sqrt(i); j++)
{
if (i%j == 0)
break;
}
if (j>sqrt(i))
{
printf("%d ", i);
count++;
}
}
printf("count=%d\n", count);
system("pause");
return 0;
}
优化4:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int i = 0;
int count = 0;
for (i = 101; i <= 200; i += 2)
{
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", count);
system("pause");
return 0;
}