Print all prime numbers within 0-100
First of all, we need to understand the definition of prime number: a number that can only be divisible by 1 and itself is a prime number, eg: 2 3 5 7……
The first is the code I wrote for the first time, followed by other codes.
#include <stdio.h>
int main()
{
int x;
for (x = 2; x <= 100; x++)
{
int i;
int n = 1;
for (i = 2; i < x; i++)
{
if (x%i == 0)
{
n = 0;
break;
}
}
if (n == 1)
{
printf("%d ", x);
}
}
printf("/n");
return 0;
}
I have also sorted out several other methods later.
Method 1: Trial division
方法一:试除法
int main()
{
int i = 0;
int count = 0;
// 外层循环用来获取100~200之间的所有数据,100肯定不是素数,因此i从101开始
for (i = 101; i <= 200; i++)
{
//判断i是否为素数:用[2, i)之间的每个数据去被i除,只要有一个可以被整除,则不是素数
int j = 0;
for (j = 2; j<i; j++)
{
if (i%j == 0)
{
break;
}
}
// 上述循环结束之后,如果j和i相等,说明[2, i)之间的所有数据都不能被i整除,则i为素数
if (j == i)
{
count++;
printf("%d ", i);
}
}
printf("\ncount = %d\n", count);
return 0;
}
The defect of the above method: more than half of the data of i is definitely not a multiple of i. The above has performed many meaningless calculations. Therefore, the following
method can be used to optimize
Method 2: Every time a piece of data is obtained, only need to be detected: [2, i/2] Whether there is an element in the interval that can be divisible by 2i, it can show that i is not a prime number
int main()
{
int i = 0;//
int count = 0;
for (i = 101; i <= 200; i++)
{
//判断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("\ncount = %d\n", count);
return 0;
}
Method two still contains some repeated data, and then optimize:
if i can be divisible by any data between [2, sqrt(i)], then i is not a prime number.
Reason: if m can be anywhere between 2 ~ m-1 If an integer is divisible, one of its two factors must be less than or equal to sqrt(m) and the other greater than or equal to sqrt(m).
int main()
{
int i = 0;
int count = 0;
for (i = 101; 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("\ncount = %d\n", count);
return 0;
}
Method 4
Continue to optimize method three, as long as i is not divisible by any data between [2, sqrt(i)], i is a prime number, but in actual operation i need not gradually increase from 101 to 200, because 2 and 3 Besides, no two consecutive adjacent data will be prime at the same time
int main()
{
int i = 0;
int count = 0;
for (i = 101; i <= 200; i += 2)
{
//判断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("\ncount = %d\n", count);
return 0;
}