-1

I'm trying to do Project Euler Problem 1 in Python (http://projecteuler.net./problem=1) and I'm using a while loop to loop to 1000:

from collections import Counter

x = 0
target = 1000
correctMultiples = list()
while x < target:
    x += 1
    if x % 3 == 0 or x % 5 == 0:
        correctMultiples.append(x)

print(str(correctMultiples) + ' are multiples of 3 or 5')

print('The sum of the multiples of 3 or 5 under 1000 is, ' + str(sum(correctMultiples))) # For some reason, 1000 over, answer is 233168 NOT 234168

This works but the answer I'm getting is 1000 over. I get 234168 instead of 233168.

I've tried checking for duplicates: (following How to find duplicate elements in array using for loop in Python?)

duplicates = Counter(correctMultiples)
print([i for i in duplicates if duplicates[i] > 1])

but I don't think there can be duplicates can they? becuase I'm using if x % 3 or ...

I know this isn't the most efficient method, but still... why doesn't it work? Can anyone help me find why the answer is 1000 over? Thanks

Community
  • 1
  • 1
ᔕᖺᘎᕊ
  • 2,971
  • 3
  • 23
  • 38

2 Answers2

2

You include 1000 in your loop, while the question ask for numbers below 1000.

Here you increment after doing the boundary check, so when x==999 you will still run the loop:

while x < target:
    x += 1

This would be so much easier with a for loop:

for x in range(1000):

range does not include the last element.

Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
0

You are including the number 1000 in your loop, because in the last iteration, x is 999 and gets increased once more.

A better solution would be the construct

for x in range(1,1000):
    ...

which includes all x from 1 to 999 and doesn't compare to 1000 on each iteration.

Stefan
  • 2,460
  • 1
  • 17
  • 33