列印 100 到 200 之間的所有質數(素數),並統計個數。
i += 2)。sqrt(i):若無因數則為質數。j += 2。#include <stdio.h>
#include <math.h>
int main() {
int count = 0;
for (int i = 101; i <= 199; i += 2) { // 只檢查奇數
int limit = (int)sqrt(i);
int j;
for (j = 3; j <= limit; j += 2) { // 只用奇數試除
if (i % j == 0) break;
}
if (j > limit) { // 沒找到因數
printf("%d ", i);
count++;
}
}
printf("\ncount=%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
count=21
sqrt(199)/2 ≈ 7 次。