python - 我可以在 for 循环中扩展范围吗?
问题描述
这是来自 Project Euler 网站的问题,我似乎无法正确解决。如果我要除的数字不能被 x 整除,我想扩展 for 循环的范围。问题在顶部。有任何想法吗?
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def main():
num = 0
to = 20
for num in range(1, to):
isDivisible = True
for x in range(1, 20):
if num % x != 0:
isDivisible = False
to += 1 #Here I try to extend the loop
continue
if isDivisible:
print(num)
break
main()
解决方案
我不确定这是不是真的,但是:
def f(x):
z = 1
for i in range(1, x + 1):
for i_2 in range(1,i + 1): #Check the multipliers! For example, since the number 9 is multiplied by 3 before, if it is multiplied by 3 again, it becomes a layer.
if i % i_2 == 0 and ( z * i_2 ) % i == 0:
z *= i_2
break
print(z)
f(20)
232792560
推荐阅读
- python - NumPy np.zeros() 无法将多维形状解释为数据类型
- javascript - Vanilla Javascript Modal一旦点击就不会出现
- javascript - 如何在python烧瓶环境中用javascript打开一个json文件
- c# - C# Linq ANY vs ALL - 性能
- c# - 相机图像的位图访问冲突异常
- javascript - 如何在 ScrollView 中保持位置?反应原生
- sql - 有没有办法使用 Impala 忽略精度误差的损失?
- kubernetes-helm - Helm:覆盖依赖图表中的值
- python - 以特定模式读取数据组
- typescript - NextJs:无法执行从 TSX 中的 .ts 文件导入的函数,抛出 ModuleNotFound 错误