当前位置:网站首页>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='') #按格式输出素数
上面的程序给出了比较详细的注释,以便新手小白参考。程序的思路设计并不是最优的,是“笨办法”,欢迎各位大佬指正错误或者给出更优质的思路。
我是一只想成为鲲鹏的菜鸟,大家的鼓励是我前进的动力,欢迎大家点赞收藏评论哦!
边栏推荐
- [中国近代史] 第六章测验
- hashCode()与equals()之间的关系
- Leetcode. 3. Longest substring without repeated characters - more than 100% solution
- 使用Spacedesk实现局域网内任意设备作为电脑拓展屏
- 5.MSDN的下载和使用
- 这次,彻底搞清楚MySQL索引
- 2.C语言矩阵乘法
- Thoroughly understand LRU algorithm - explain 146 questions in detail and eliminate LRU cache in redis
- 透彻理解LRU算法——详解力扣146题及Redis中LRU缓存淘汰
- FAQs and answers to the imitation Niuke technology blog project (I)
猜你喜欢
3. Number guessing game
8. C language - bit operator and displacement operator
FAQs and answers to the imitation Niuke technology blog project (III)
This time, thoroughly understand the MySQL index
canvas基础2 - arc - 画弧线
记一次猫舍由外到内的渗透撞库操作提取-flag
[面試時]——我如何講清楚TCP實現可靠傳輸的機制
FAQs and answers to the imitation Niuke technology blog project (II)
4. Binary search
5. Download and use of MSDN
随机推荐
【九阳神功】2021复旦大学应用统计真题+解析
1. First knowledge of C language (1)
5.MSDN的下载和使用
1.C语言矩阵加减法
canvas基础1 - 画直线(通俗易懂)
hashCode()与equals()之间的关系
[中国近代史] 第五章测验
A comprehensive summary of MySQL transactions and implementation principles, and no longer have to worry about interviews
4.二分查找
Differences among fianl, finally, and finalize
为什么要使用Redis
[中国近代史] 第九章测验
20220211-CTF-MISC-006-pure_ Color (use of stegsolve tool) -007 Aesop_ Secret (AES decryption)
Relationship between hashcode() and equals()
Reinforcement learning series (I): basic principles and concepts
Questions and answers of "basic experiment" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology
简单理解ES6的Promise
2022泰迪杯数据挖掘挑战赛C题思路及赛后总结
Mortal immortal cultivation pointer-2
6. Function recursion