在 c++ 中
for (auto i = min; i < sqrt_max; i++ ) {
for (auto j = i; i*j <= sqrt_max; j++) {
我正在尝试在python中做完全相同的事情
for i in enumerate(range(min, sqrt_max + 1)):
for j in enumerate(range(min, i * j < sqrt_max + 1)):
我得到undefined name j
- 不要在两个循环中使用
enumerate(..)
。enumerate
采用为其参数中的每个element
返回一对index, element
的东西。 - 您不能像这样使用
j
,因为它仅在 for 循环主体中定义。
你想要的是下面这样的东西:
for i in range(min, sqrt_max): # i will not take the value of sqrt_max.
for j in range(i, 1 + sqrt_max//i): # i is defined here within range, but j is not.
...