Print all primes of 100-200.
Primes: 1 and the number itself is not in addition to the other factors referred to as primes.
Method: trial division
A wording:
[Thinking] : The flag as a flag, whether the flag is a prime number. flag is set to 1, that is not a prime number. flag is 0, it is a prime number. Determining whether the print for the outer loop, count ++ whether the count bits.
[Reflect] Code:
int main()
{
int count = 0; // 计算素数的个数
int flag = 0; // 标志位,标记是否为素数
for (int i = 100; i <= 200; i++)
{
flag = 0;
for (int j = i - 1; j >= 2; j--)
{
if (i%j == 0)
{
flag = 1; // 将flag置为1,标识不是素数
break;
}
}
if (!flag) // 如果flag 为0标识为素数, !flag即为非0,则count++
{
count++;
printf("%d ", i);
}
}
printf("\n总共有%d个素数\n", count);
system("pause");
}
Written two:
[Thought]: After the cycle for a 1-i-1, j is the value determined by whether i is a prime number, code comments are described in detail in
[Reflect] Code:
int main()
{
int count = 0;
for (int i = 100; i <= 200; i++)
{
// 判断i是否为素数
// 检查 2-i-1个数是否是i的因子
int j = 0;
for (j = 2; j <= i - 1; j++)
{
if (i%j == 0)
break;
}
// 在此处跳出循环的有从2-i-1检测完的,也有不符合要求break,跳出循环来到这一步的。
// 如果j > i-1;说明从2到i-1的数全部都检测了一遍,没有i的因数
if (j > i - 1)
{
count++;
printf("%d ", i);
}
}
printf("\n总共有%d个素数\n", count);
system("pause");
}
Can also be optimized
[Thinking]: calculate whether the time factor i, you only need to calculate the root number i, can. Because a number x is equal to the square of the square root of x, that is, if the product of two numbers is equal to x, then the two numbers must have a square root of x is less than, greater than the other square root of x . For example 64,8 8 = 64, and 2 32 = 64,2 less than 8, more than 32 large 8; and 4 = 64,4 * 16 is smaller than 8, greater than 16 8. Therefore, to calculate the ratio of sqrt (x) can be a small number.
[Reflect] Code:
#incldue <math.h>
int main()
{
int count = 0;
for (int i = 100; i <= 200; i++)
{
// 判断i是否为素数
// 2 - i-1
int j = 0;
for (j = 2; j <= sqrt(i); j++)
{
if (i%j == 0)
break;
}
//
if (j > sqrt(i))
{
count++;
printf("%d ", i);
}
}
printf("\n总共有%d个素数\n", count);
system("pause");
}
Of course, we can continue to optimize
[Thinking]: because prime number, can not be even. Therefore, the outermost loop, a for (int i = 100; i <= 200; i ++) replaced for (int i = 101; i <= 200; i + = 2). The number of such cycles can be reduced by half. Greatly improves the efficiency calculation.
[Reflect] Code:
int main()
{
int count = 0;
for (int i = 101; i <= 200; i+= 2)
{
// 判断i是否为素数
// 2 - i-1
int j = 0;
for (j = 2; j <= i/2; j++)
{
if (i%j == 0)
break;
}
//
if (j > i/2)
{
count++;
printf("%d ", i);
}
}
printf("\n总共有%d个素数\n", count);
system("pause");
}