【问题标题】:Am I able to extend the range in a for loop?我可以在 for 循环中扩展范围吗?
【发布时间】:2021-06-19 23:38:31
【问题描述】:

这是来自 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()

【问题讨论】:

  • 如果您不需要以某种方式扩展 for 循环,似乎 while 循环可能更适合这里 - 而不是从 0 到 20(或其他任意数字),继续运行(并且递增)虽然不是可分的。范围已经在你的 for 循环开始时定义了,所以不能从它里面扩展

标签: python python-3.x for-loop range


【解决方案1】:

我不确定这是不是真的,但是:

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

【讨论】:

  • 非常感谢!有道理。
猜你喜欢
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 2012-08-25
  • 2021-10-25
  • 1970-01-01
  • 2018-09-08
  • 2013-12-17
  • 1970-01-01
相关资源
最近更新 更多