题目
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.
解答
10以内能被3或5整除的数是3,5,6,9,加和是23.
求1000以内这样的数加和是多少?
新手可能一条for循环,里面再套if语句看是不是能整除,然后加和。
10以内要循环9个数。而如果我用乘法,对于3,只需要1:3*33个数就够了。对于5来说,1个数就够了。所以总共是4个数。
R
M <- function(N, x) {
sum(1:floor((N-1)/x) * x)
}
M(1000, 3) + M(1000, 5) - M(1000, 15)
Python
def M(N, x):
n = (N-1) // x
return sum([x * i for i in range(1, n+1)])
M(1000, 3) + M(1000, 5) - M(1000, 15)
为什么要减掉能整除15的?因为在整除3和整除5的数中均会出现,重复加了,所以减掉。
答案
>>> M(1000, 3) + M(1000, 5) - M(1000, 15)
233168