貌似第一题是最简单的一道题——
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.
求1000以内3或者5的倍数的和,最简单的实现是一个for循环,甚至连一般的算法都用不上,想来也是开山第一题给的简单些吧。
不过这样直接计算的效率不高,当范围取得很大的时候,计算的时间将会很长。主要是历遍所有可能的取值耗时繁琐,对于一般的解法,多数是分别取3和5为步长,求和,然后再除去15的倍数。这样效率略微高一些,耗时也是原来的0.6倍。
C语言实现:
C |copy code |?
01 /*========================================================================
02 # FileName: Main.c
03 # Author: hsyyf
04 # Email: 931107419@qq.com
05 # HomePage: http://www.hsyyf.me
06 # LastChange: 2012-06-24 12:30:12
07 ========================================================================*/
08 #include<stdio.h>
09 int main(void)10 {
11 int i,sum;12 sum=0;13 for(i=1;i<1000;i++)14 {
15 if(i%3==0 || i%5==0)16 sum=sum+i;17 }
18 printf("%d",sum);19 return 0;20 }
结果是233168.
管理员 hsyyf: 2012年06月24日 下午6:00 ∇地下1层