简体   繁体   English

ProjectEuler incesption 中的错误答案?

[英]Wrong answer in ProjectEuler incesption?

The goal of the code is to find the sum of all multiples of 3 and 5 under 1000 (natural numbers, so starting from 1).代码的目标是求 1000(自然数,所以从 1 开始)下所有 3 和 5 的倍数之和。

My code:我的代码:

sum_of_3 = 0
sum_of_5 = 0

for a in range (0, 1000, 3):
    sum_of_3 += a
print(sum_of_3)
Output: 166833

for b in range (0, 1000, 5)
    sum_of_5 += b
print (sum_of_5)
Output: 99500

total_sum = sum_of_3 + sum_of_5
print (total_sum)
Output: 266333

My output is wrong.我的 output 是错误的。 The correct code and output is:正确的代码和 output 是:

nums = range (1, 1000)
sumofmultiples = 0
for i in nums:
    if i % 3 == 0 or i % 5 == 0:
        sumofmultiples = i + sumofmultiples
print (sumofmultiples)
Output: 233168

Why am I getting a different answer?为什么我得到不同的答案?

When doing the collection of numbers in two seperate calculation, you add some numbers twice.在两次单独计算中收集数字时,您将一些数字相加两次。

Have a look at 15, ist will be added onec since its a multipe of 3 and again, since its a multiple of 5.看一下 15,因为它是 3 的倍数,所以 ist 将被添加 onec,因为它是 5 的倍数。

If you want to keep your coed, you should check in your second for loop, whether the number ist dividable by 3.如果你想保持你的男女同校,你应该检查你的第二个 for 循环,这个数字是否可以被 3 整除。

You are calculating some value twice, For Example 15, 30, 45, 60, 75, 90. 105 and so on...您正在计算某个值两次,例如 15、30、45、60、75、90. 105 等等...

In your first loop you add some value such as 15, 30, 45 Then in your next loop you again add them!在您的第一个循环中添加一些值,例如 15、30、45 然后在您的下一个循环中再次添加它们!

In the correct code you can see there is a "Logical OR" operator which adding 15, 30, 45.... only for once在正确的代码中,您可以看到有一个“逻辑或”运算符,它只将 15、30、45.... 相加一次

I hope you get it now Thank you.我希望你现在明白了谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM