Reputation: 25
The following program gives the sum of all numbers that are divisible by either 3 or 5 below a given input number. The problem I am facing is that it doesn't correctly output sum for n = 100. The solution for n = 100 should be 2318, but my program gives me 2633. I can't figure out the problem, since it also gives the right sum for n = 10 correctly.
#!/bin/python3
import sys
import math
arr = []
sum1 = 0
sum2 = 0
t = int(input().strip())
while t < 1 or t > 10**5:
print()
t = int(input().strip())
for i in range(t):
n = int(input().strip())
arr.append(n)
for x in range (0, len(arr)):
sum1 = 0
sum2 = 0
for b5 in range (0, arr[x], 5):
sum1 = sum1 + b5
for b3 in range (0, arr[x], 3):
sum2 = sum2 + b3
sum = sum1 + sum2
print(sum)
Edit: After all the good feedback, I came up with the idea to exclude the numbers that are being added twice in the original program, by adding an if statement as follows:
for b5 in range (0, arr[x], 5):
sum1 = sum1 + b5
if b5%3 == 0:
sum1 = sum1 - b5
for b3 in range (0, arr[x], 3):
sum2 = sum2 + b3
It isn't as elegant, but I still wanted to add it.
Upvotes: 0
Views: 215
Reputation: 5430
The excellent @trincot answers are clever Python. For completeness, the looping answer below shows how your original logic should have been structured.
mysum = 0
limit = 100
for x in range(limit):
if (x % 5 == 0) or (x % 3 == 0):
mysum += x
Upvotes: 1
Reputation: 350272
The problem is that this counts double the numbers that are both multiples of 3 and of 5.
The easy solution is to subtract those from your sum.
Note that your loops are bit overkill, as the sum
function can take the range
expression directly as argument.
So:
n = 100
total = sum(range (0, n, 5)) + sum(range (0, n, 3)) - sum(range (0, n, 3*5))
print(total)
You can avoid the (implicit) loops by solving this with the formula for Triangular numbers:
def sum_mul(n, divisor):
quot = (n - 1) // divisor
return (quot * (quot + 1) // 2) * divisor
n = 100
total = sum_mul(n, 3) + sum_mul(n, 5) - sum_mul(n, 3*5)
print(total)
Upvotes: 2