打印100-200之间的素数
编程思路:
素数判断规则:只能被1和它本身整除的数
- 第一步:先找出100-200的整数。
- 第二步:在这些数中筛选出只能被1和它本身出能整除的数打印出来。
代码示例:
#include <stdio.h>
#include <math.h>int main()
{int i = 0;int count = 0;for (i = 101; i <= 200; i+=2){int j = 0;int n = 1;for (j = 2; j <= sqrt(i); j++)//sqrt()是数学库函数,用于开平方。{if (i % j == 0){n = 0;break;}}if (1 == n){printf("%d ", i);count++;}}printf("\n素数个数为:%d\n", count);return 0;
}
运行结果:
101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
素数个数为:21
此代码筛掉了偶数,又运用对数字开平方,用开平方以内的数字来判断是不是素数,提高了运行效率。