topic:
- For any number greater than 3, determine whether it is a prime number
analysis:
- (1) Prime number: Except 1 and itself, it cannot be divisible by any other number
- (2) Assuming that the number is n, only need to check whether it is divisible by 2 ~ n/2 (even if it only needs to be judged to the radical number n).
C language problem solving
- The fourth step is quite messy to write, and you have to judge the small numbers of 3, 4, and 5. Only personal ideas
- And pay attention to type conversion (int)n/2
#include<stdio.h>
int main()
{
int n, i;
printf("请输入n的值:\n");
scanf("%d", &n);
for(i=2;i <= n/2; i++)
{
if (n%i == 0)
{
printf("%d, 不是素数\n", n);
break;
}
}
if (i >= (int)n/2 && n != 4)
printf("%d, 是素数\n", n);
return 0;
}
- Supplement: Actually no type conversion is required
python problem solving
- The inherent else syntax behind the python for statement eliminates the if judgment at the end of the C language, which is a bit more concise
n = int(input("请输入要判定的数字:"))
for i in range(2, int(n/2) + 1):
if n%i == 0:
print("%d, 不是素数"% n)
break
else:
print("%d, 是素数"% n)