今天在网上刚看到的这个网站,很感兴趣,想一直做下去,尽量把里边的题都做了。
第一道题是用python做的,刚学python,里边的好多东西还不是太清楚,也是第一次做这个题,可能如不了大神的法眼,我会一直努力的。
题目:
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.
算法:
#!/usr/bin/env python
sum = 0
for i in range(0,1000):
if i%3==0 or i%5==0:
sum += i
print sum
结果:233168
---------------------------------------------------分割线------------------------------------------------------
$x = 1000;
echo 1.5*(int)(($x-1)/3)*(int)(($x+2)/3) + 2.5*(int)(($x-1)/5)*(int)(($x+4)/5) - 7.5*(int)(($x-1)/15)*(int)(($x+14)/15);
这是在下边看到别人的答案,觉得很好,乍一看还没看懂,就分析了一下:
1.5*(int)(($x-1)/3)*(int)(($x+2)/3)是1000以内能被3整除的数的和,后边两个是能被5和15整除的和。
求和过程是基于等差数列的求和公式进行的
S = (a1+an)*n/2
=a1*(1+n)*n/2
=(a1/2)*n*(1+n)
这个结果就和他的求和公式对应起来了。
拿到这道题想都没想就用一个for循环搞定,看来再怎么简单的问题都要先思考再说。