Project Euler Problem 1 - Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
对给定的max和k,小于max的k的倍数的个数为
c = (max - 1) / k
值分别为
k, 2k, ... , ck,
则总和为
k(1 + 2 + ... + c) = k(1+c)c/2
Python代码:
max = 1000 - 1
a = 3; b = 5
c = a * b
def f(k):
return (1 + k) * k / 2
res = f(max / a) * a + f(max / b) * b - f(max / c) * c
print res
时间复杂度O(1)
空间复杂度O(1)
posted on 2012-12-23 10:22 ZeroSnake0 阅读(118) 评论(0) 收藏 举报
浙公网安备 33010602011771号