求指定区间内能被3,5和7整除的数的个数
输入格式:
在一行中从键盘输入2个正整数a,b(1<=a<b<=10000000),用空格隔开。
输出格式:
在一行输出大于等于a且小于等于b的能被3,5和7整除的数的个数。
这是一开始做的,没有注意大题目需要用集合实现,不过运行起来也是对的。
python
a,b=list(map(int,input().split()))
f=False
total=0
for i in range(a,b+1):
if i%3==0 and i%5==0 and i%7==0:
total+=1
f=True
if not f:
print("0")
else:
print(total)
后面想在原题的基础上略微改一下:
python
a,b=list(map(int,input().split()))
s=set(range(a,b+1))#或者s={x for x in range(a,b+1)}
total=0
f=False
for i in s:
if i%3==0 and i%5==0 and i%7==0:
total+=1
f=True
if not f:
print("0")
else:
print(total)
虽然运行结果是正确的,但是把(1<=a<b<=10000000)存入集合里会内存很大,所以最后题报了内存超限。
python
a,b=list(map(int,input().split()))
s=set()
f=False
for i in range(a,b+1):
if i%3==0 and i%5==0 and i%7==0:
s.add(i)
f=True
if not f:
print("0")
else:
print(len(s))
上面这个代码是完全正确的。
python
a,b=list(map(int,input().split()))
s=set()
f=False
start=(a+104)//105*105
for i in range(start,b+1,105):
s.add(i)
f=True
if not f:
print("0")
else:
print(len(s))
虽然正确,但是运行速度太慢,所以进行了修改,3.5.7的最小公倍数是105,所以有了start=(a+104)//105*105这一步,意思是第一个>=a的105倍数。但不能直接(a,b,105),因为不能保证a一开始就是105的倍数。
python
import math
a,b=list(map(int,input().split()))
s=set()
f=False
start=math.ceil(a/105)*105
for i in range(start,b+1,105):
s.add(i)
f=True
if not f:
print("0")
else:
print(len(s))
还可以引入math函数,ceil的意思是向上取整,//的意思是向下取整,举个例子假设a是104或105
当104时,在start=(a+104)//105*105中,先对1.9进行向下取整到1,再1*105,
在math.ceil(a/105)*105中,start是先对0.99向上取整到1,再*105。
之所以在start=(a+104)//105*105中是加104,而非105,因为若是a初始就为105,会变为210//105=2*105,这样在for i in range(start,b+1,105):里就不对了,本来初始是105的,现在变为210,会使最后结果少统计。
| 英文 | 含义 | Python实现 |
|---|---|---|
| floor | 向下取整(取 ≤ x 的最大整数) | int(x) 或 math.floor(x) |
| ceil | 向上取整(取 ≥ x 的最小整数) | math.ceil(x) |