Reputation: 7
I've decided I want to work on the Euler problems in order to improve my Python skills, but I ran into a problem with the first one. You see, I wrote the program I thought would work trying to get an answer, and compared it to the one found on the solutions page located here. Here is the code that I wrote:
total = 0
for x in range(1000):
if x % 5 != 0 and x % 3 != 0:
total += x
print(total)
This gives me the answer 266,332, when the correct answer is 233,168 according to the solution linked before. I don't know why I got the wrong answer, and any help would be appreciated. Thanks!
Upvotes: 0
Views: 95
Reputation: 1
try this:
def sumOfMultiples(number):
sum = 0
for i in range(1,number):
if i % 2 == 0 or i % 3 == 0:
sum += i
return sum
print (sumOfMultiples(15))
Upvotes: -1
Reputation: 1968
You are using the wrong condition. You have to test, when the rest is 0? With 3 and with 5. Additionally you have to use OR instead AND because you want both group of numbers.
If you use AND you are going to get only the numbers that are multiple of both, multiple of 3 and multiple of 5.
Try:
total = 0
for x in range(1000):
if x % 5 == 0 or x % 3 == 0:
total += x
print(total)
Upvotes: 1
Reputation: 49318
You're missing a not
in your application of De Morgan's Law:
total = 0
for x in range(1000):
if not (x % 5 != 0 and x % 3 != 0):
total += x
print(total)
not (x % 5 != 0 and x % 3 != 0)
is equivalent to x % 5 == 0 or x % 3 == 0
, the latter of which is stated in the page you link as the equivalent not x%5 or not x%3
.
Upvotes: 1
Reputation: 2534
A couple of things are wrong with the program. For starters, your if
statement checks the wrong condition--it checks to see whether or not it is NOT divisible by 3 or 5. It should be if x%3==0 or x%5==0:
Second, you have an indentation error, so nothing is being executed by the if
statement. Indent the total+=x
statement.
Your final code will look like this:
total = 0
for x in range(1000):
if x % 5 == 0 or x % 3 == 0:
total += x
print(total)
Best of luck, and happy coding!
Upvotes: 0