Prime number judgment C language and python

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()
{
    
    
	// 1.获取n的值
	int n, i;
	printf("请输入n的值:\n");
	scanf("%d", &n);
	// 2. 创建 作为初始除数i=2
	for(i=2;i <= n/2; i++)
	{
    
    
		// 3. 判断 2~ n/2 的是能否整除,能整除就得出 不是素数,结束循环
		if (n%i == 0)
		{
    
    
			printf("%d, 不是素数\n", n);
			break;
		}
	}
	// 4. 当i>= n/2时,表示循环全部结束,输出n是素数(这里 i > n/2 的情况是 n==3,i=1,且 n 不能为4,因为是四,两个printf语句都将输出) 
	if (i >= (int)n/2 && n != 4)
		printf("%d, 是素数\n", n);
	return 0;
}
  • Supplement: Actually no type conversion is required
    Insert picture description here

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 与for对齐
else:
    print("%d, 是素数"% n)

Guess you like

Origin blog.csdn.net/pythonstrat/article/details/112647951