Problem 1: Multiples of 3 and 5

本文提供了一个使用Python解决Project Euler中Problem1的方法。该问题要求找到1000以下所有3或5的倍数之和。通过创建一个列表来存储这些倍数,并去除重复项后求和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小白一枚,python解法,共同学习,一起进步。

Problem 1: Multiples of 3 and 5

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

解题思路:

找出所有3和5的倍数,不超过最大数n,去重求和即可。

 

 1 l = []  # 存放3和5倍数的数
 2 n = 1000  # 最大数
 3 for i in range(1, n):
 4     if 3*i >= n:  # 如果大于最大数,终止
 5         break
 6     l.append(3*i)
 7 for i in range(1, n):
 8     if 5*i >= n:
 9         break
10     l.append(5*i)
11 l = set(l)  # 去重,譬如15 30之类的
12 print(sum(l))

%time %run ol001.py
233168
Wall time: 2 ms

 

转载于:https://www.cnblogs.com/Quxiaolong2020/p/7903217.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值