Skip to content

Commit 49b2dcf

Browse files
committed
add two notes
1 parent a6d113b commit 49b2dcf

2 files changed

Lines changed: 94 additions & 0 deletions

File tree

allprime.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/home/taoyan/anaconda3/bin/python3
2+
# -*- coding: UTF-8 -*-
3+
# filename:allprime.py
4+
# author by:taoyan
5+
6+
'''
7+
这个题目跟上次那个判断质数的题目差不多,先给定一个范围,遍历,判断是不是质数,如果是的话输出
8+
'''
9+
10+
from math import sqrt
11+
def is_prime(n):
12+
if n==1:
13+
return False
14+
for i in range(2,int(sqrt(n))+1):
15+
if n % i==0:
16+
return False
17+
return True
18+
#用户输入区间
19+
lower=int(input("请输入区间的最小值: "))
20+
upper=int(input("请输入区间的最大值: "))
21+
for num in range(lower,upper+1):
22+
if is_prime(num):
23+
print(num)

is_prime.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#!/home/taoyan/anaconda3/bin/python3
2+
# -*- coding: UTF-8 -*-
3+
# filename:is_prime.py
4+
# author by:taoyan
5+
6+
'''
7+
一个大于1的自然数,除了1和它本身外,不能被其他自然数(质数)整除,换句话说就是该数除了1和它本身意外不再有其它因数
8+
一般判断思路是:
9+
在一般领域,对于正整数n,如果用2到√n之间的所有整数去除,均无法整除,则n为质数(合数)
10+
'''
11+
#说先根据判断思路定义一个函数
12+
13+
from math import sqrt
14+
def is_prime(n):
15+
if n==1:
16+
return False
17+
for i in range(2,int(sqrt(n))+1):
18+
if n % i==0:
19+
return False
20+
return True
21+
22+
number=int(input("请输入一个整数:"))
23+
while is_prime(number):
24+
print("{0}是质数!".format(number))
25+
break
26+
else:
27+
print("{0}不是质数!".format(number))
28+
29+
30+
'''
31+
还有一些其它的做法,但是有点繁琐,效率不高,这里也可以参考一下:
32+
33+
#用户输入数字
34+
num=int(input("请输入一个数字: "))
35+
#质数大于1
36+
if num>1:
37+
#查看因子
38+
for i in range(2,num):
39+
if num % i ==0:
40+
print("{0}不是质数!".format(num))
41+
break
42+
else:
43+
print("{0}是质数!".format(num))
44+
else:
45+
print("{0}不是质数!".format(num))'
46+
47+
'''
48+
49+
'''
50+
下面这种做法也是利用平方根来减少运算量
51+
52+
#导入模块math
53+
import math
54+
#用户输入数字
55+
num=int(input("请输入一个数字: "))
56+
#质数大于1
57+
if num>1:
58+
#找到平方根,减少计算量
59+
square_num=math.floor(num**0.5)
60+
#查找因子
61+
for i in range(2,(square_num+1)):
62+
if (num % i)==0:
63+
print("{0}不是质数,是合数!".format(num))
64+
break
65+
else:
66+
print("{0}是质数!".format(num))
67+
#如果输入的数字小于或等于1,不是质数
68+
else:
69+
print("{0}不是质数,也不是合数!".format(num))
70+
71+
'''

0 commit comments

Comments
 (0)