I am trying to find the sum of the multiples of 3 or 5 of all the numbers upto N.
This is a practise question on HackerEarth. I was able to pass all the test cases except 1. I get a time and memory exceeded error. I looked up the documentation and learnt that int can handle large numbers and the type bignum was removed.
I am still learning python and would appreciate any constructive feedback.
Could you please point me in the right direction so I can optimise the code myself?
test_cases = int(input())
for i in range(test_cases):
user_input = int(input())
sum = 0
for j in range (0, user_input):
if j % 3 == 0:
sum = sum + j
elif j % 5 == 0:
sum = sum + j
print(sum)
答案 0 :(得分:0)
在这些问题中,尝试使用一些数学来找到一个直接的解决方案而不是强制它。
您可以在n下计算k的倍数,然后计算它们的总和。
例如,当k = 3且n = 13时,你有13 // 3 = 4倍 他们的总和是3 * 1 + 3 * 2 + 3 * 3 + 3 * 4 = 3 *(1 + 2 + 3 + 4)
然后,使用关系:1 + 2 + .... + n = n *(n + 1)/ 2
要求3和5的倍数,你可以求和3的倍数,加上5的倍数之和,减去你计算两次的数:15的倍数。
所以,你可以这样做:
def sum_of_multiples_of(k, n):
"""
Returns the sum of the multiples of k under n
"""
# number of multiples of k between 1 and n
m = n // k
return k * m * (m+1) // 2
def sum_under(n):
return (sum_of_multiples_of(3, n)
+ sum_of_multiples_of(5, n)
- sum_of_multiples_of(15, n))
# 3+5+6+9+10 = 33
print(sum_under(10))
# 33
# 3+5+6+9+10+12+15+18 = 78
print(sum_under(19))
# 78