gpt4 book ai didi

python - 如何找到200到400之间的友好数字?

转载 作者:太空宇宙 更新时间:2023-11-03 20:20:32 25 4
gpt4 key购买 nike

我仅使用 for 和 if 循环来查找 200 到 400 之间的友好数字,即只有 220 和 287。我尝试使用此代码,但由于某种原因,它没有打印这两个数字。代码哪里错了?我不想使用函数。

for num in range(200 , 401):
sum1 = 0
for i in range(1 , num + 1):
if num % i == 0:
sum1 += i
for num2 in range(200 , 401):
sum2 = 0
for j in range(1 , num2 + 1):
if num2 % j == 0:
sum2 += j
if sum1 == num2 and sum2 == num:
print("{} and {} are amicable numbers.".format(num , num2))

我希望输出为“220 和 287 是友好的数字。”,但终端将其留空,没有任何错误消息。

最佳答案

amicable numbers您正在寻找的是 220 和 284。数字不是 proper divisor本身,因此您应该调整范围以排除该数字作为其自身的除数。另外,您的 if 语句仅在 num2 == 400 时比较总和,因为您的缩进已关闭。我发现所有嵌套循环都有点难以阅读,所以这里有一种对我来说似乎更干净的方法。

for a in range(200, 401):
b = sum(j for j in range(1, a) if a % j == 0)
x = sum(j for j in range(1, b) if b % j == 0)
if a == x:
print(f'{a} and {b} are amicable numbers');

# 220 and 284 are amicable numbers
# 284 and 220 are amicable numbers

关于python - 如何找到200到400之间的友好数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58189899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com