Table of contents
(1) Characteristics of prime numbers: they can only be divisible by 1 and itself
(3) The running results are as follows
(1) Characteristics of prime numbers: they can only be divisible by 1 and itself
That is, you can use a for loop and use an if statement to determine whether there is an integer other than 1 and itself. If so, it is not a prime number.
(2) The code is as follows:
void is_prime()
{
int i = 0;
int j = 0;
int flag = 0;
printf("请输入要判断的数:");
scanf("%d",&i);
for (j = 2; j < i; j++)
{
if (i % j == 0)
{
flag++;
}
}
if (flag == 0)
{
printf("%d是素数\n", i);
}
}
int main()
{
is_prime();
return 0;
}
(3) The running results are as follows
(4) Function extension
Use the is_prime function implemented above to print prime numbers between 100 and 200.
Change the value of i through nested for loops to judge one by one
The modified function is as follows
void is_prime()
{
int i = 0;
int j = 0;
int flag = 0;
for (i = 100; i < 201; i++)
{
flag = 0;
for (j = 2; j < i; j++)
{
if (i % j == 0)
{
flag++;
}
}
if (flag == 0)
{
printf("%d\n", i);
}
}
}
int main()
{
is_prime();
return 0;
}
The running results are as follows:
So the prime numbers between 100 and 200 are 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199 These 21.