I'm looking to optimize a simple sum calculator used in Project Euler+. The premise is simple: Find the sum of all the numbers divisible by 3 or 5 under X.
At first I did it like so:
def main(testCases):
final_answer = []
for x in range(testCases):
answer = 0
test = long(input())
for num in range(test):
if (num % 5 == 0 or num % 3 == 0):
print(num)
answer += num
final_answer.append(str(answer))
print('\n'.join(final_answer))
main(input())
Which worked alright. Then I realized it couldn't handle anything like 10,000,000,000 at all, which was bad, so I tried:
def main(testCases):
for x in range(testCases):
answer = 0
num = input()
Temp = (num - 1) // 3
answer += (Temp * (3 + Temp * 3)) // 2
Temp = (num - 1) // 5
answer += (Temp * (5 + Temp * 5)) // 2
Temp = (num - 1) // 15
answer -= (Temp * (15 + Temp * 15)) // 2
print answer
main(input())
Which was way faster / capable of giant numbers. However, it seems really ugly and unoptimized, but maybe it's in my head. Can anyone help me optimize my answer?
Sample
Input:
2
10
100
Output:
23
2318