当前位置:网站首页>7-1 输出2到n之间的全部素数(PTA程序设计)
7-1 输出2到n之间的全部素数(PTA程序设计)
2022-07-06 09:22:00 【编程林黛玉】
本题要求输出2到n之间的全部素数,每行输出10个。素数就是只能被1和自身整除的正整数。注意:1不是素数,2是素数。
输入格式:
输入在一行中给出一个长整型范围内的整数。
输出格式:
输出素数,每个数占6位,每行输出10个。如果最后一行输出的素数个数不到10个,也需要换行。
输入样例:
10
输出样例:
2 3 5 7
代码(Python):
n=int(input()) #先输入n,因为input输入的是字符串,所以需要强制转换成int类型
x=0 #用来记录输出的素数个数
if n==2: #特殊情况:输入的n等于2(因为下面的循环是需要判断n是否能整除2~n-1之间的数,如果将2放入下面循环,由于它能整除2,所以会被判定为非素数而导致出错
print("%6d"%n,end='') #注意输出格式,%6d表示每个数占6位数,end=''表示结尾不回车
elif n>2: #一般情况
for i in range(2,n): #开始判断2~n(不包括n)之间的每个数
j=2 #先令每个数除以2
while i%j!=0: #如果除以j不为0,进入循环,j一直加1,直到退出循环
j+=1
if j==i: #判断退出上面while循环的原因,如果是j等于i,说明该数一直加到本身都没有遇到能整除的数
if x!=0 and x%10==0: #看它是该行输出的第几个数,以判断要不要换行:x等于0的话表示它是输出的第一个数,不用换行:x取余10等于0的话,表示输出的数是10的倍数,要换行
x+=1 #每输出一个数,x加一
print() #由于输出的数是10的倍数,表示该行输出了10个数,要换行(print默认会换行)
print("%6d"%i,end='') #按格式输出素数
else: #否则不是上面两种情况,表示该行数未满10个,则不需要换行,正常输出
x+=1 #每输出一个数,x加一
print("%6d"%i,end='') #按格式输出素数上面的程序给出了比较详细的注释,以便新手小白参考。程序的思路设计并不是最优的,是“笨办法”,欢迎各位大佬指正错误或者给出更优质的思路。
我是一只想成为鲲鹏的菜鸟,大家的鼓励是我前进的动力,欢迎大家点赞收藏评论哦!
边栏推荐
猜你喜欢

Questions and answers of "basic experiment" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology

9. Pointer (upper)

3. Input and output functions (printf, scanf, getchar and putchar)
![[au cours de l'entrevue] - Comment expliquer le mécanisme de transmission fiable de TCP](/img/d6/109042b77de2f3cfbf866b24e89a45.png)
[au cours de l'entrevue] - Comment expliquer le mécanisme de transmission fiable de TCP

PriorityQueue (large root heap / small root heap /topk problem)

2. Preliminary exercises of C language (2)

MySQL事务及实现原理全面总结,再也不用担心面试

一段用蜂鸣器编的音乐(成都)

仿牛客技术博客项目常见问题及解答(一)

编写程序,模拟现实生活中的交通信号灯。
随机推荐
[au cours de l'entrevue] - Comment expliquer le mécanisme de transmission fiable de TCP
TypeScript快速入门
1.初识C语言(1)
6. Function recursion
5.MSDN的下载和使用
Redis实现分布式锁原理详解
2. Preliminary exercises of C language (2)
Safe driving skills on ice and snow roads
重载和重写的区别
Cookie和Session的区别
2022泰迪杯数据挖掘挑战赛C题思路及赛后总结
Thoroughly understand LRU algorithm - explain 146 questions in detail and eliminate LRU cache in redis
Reinforcement learning series (I): basic principles and concepts
扑克牌游戏程序——人机对抗
[the Nine Yang Manual] 2016 Fudan University Applied Statistics real problem + analysis
MATLAB打开.m文件乱码解决办法
FAQs and answers to the imitation Niuke technology blog project (III)
string
C language Getting Started Guide
Using spacedesk to realize any device in the LAN as a computer expansion screen