5-8能被3,5和7整除的数的个数(用集合实现)

求指定区间内能被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)
相关推荐
@PHARAOH14 小时前
WHAT - git worktree 概念
前端·git
gmaajt14 小时前
mysql如何备份与恢复函数定义_mysql mysqldump导出存储对象
jvm·数据库·python
qeen8715 小时前
【数据结构】树的基本概念及存储
c语言·数据结构·c++·学习·
阿丰资源15 小时前
基于SpringBoot的在线视频教育平台的设计与实现(附源码+数据库+文档,一键运行)
数据库·spring boot·后端
qq_4609784015 小时前
Python爬虫怎么模拟手机端抓取_设置手机型号User-Agent字符串
jvm·数据库·python
一江寒逸15 小时前
数据结构与算法之美:串(字符串)——从基础操作到KMP模式匹配,吃透面试最高频的字符串考点
数据结构·面试·职场和发展
IT_陈寒15 小时前
我竟然被JavaScript的隐式类型转换坑了三天!
前端·人工智能·后端
我亚索贼六丶15 小时前
二十六. AI基础概念之如何更好的使用AI
前端
love530love15 小时前
Clink 调校指南:让 Windows CMD 拥有现代终端的便捷体验
人工智能·windows·python·cmd·clink