貌似第一题是最简单的一道题——

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语言实现:

/*========================================================================
# FileName: Main.c
# Author: hsyyf
# Email: 931107419@qq.com
# HomePage: http://www.hsyyf.me
# LastChange: 2012-06-24 12:30:12
========================================================================*/
#include
int main(void)
{
int i,sum;
sum=0;
for(i=1;i<1000;i++) { if(i%3==0 || i%5==0) sum=sum+i; } printf("%d",sum); return 0; }

结果是233168.

作者 hsyyf

《Project Euler 1》有2条评论
  1. ● time perl -e ‘$s = 0; ($_%3==0||$_%5==0) && ($s += $_) for (1..999);print $s’
    233168perl -e ‘$s = 0; ($_%3==0||$_%5==0) && ($s += $_) for (1..999);print $s’ 0.00s user 0.00s system 62% cpu 0.003 total
    perl 很快。

回复 hsyyf 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注