您的位置:首页 > 其它

Project Euler 第一题效率分析

2015-10-31 17:36 204 查看
Project Euler:

[align=left]欧拉计划是一系列挑战数学或者计算机编程问题,解决这些问题需要的不仅仅是数学功底。[/align]
[align=left]启动这一项目的目的在于,为乐于探索的人提供一个钻研其他领域并且学习新知识的平台,将这一平台打造一个有趣和休闲[/align]
的环境。

[align=left]项目主页:https://projecteuler.net[/align]
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.

解决思路

[align=left]方法一:for 循环[/align]
for (int i=0; i<1000; i++) {
if (i%3==0 || i%5==0)
sum+=i;
}


[align=left]方法二:等差数列求和[/align]

sum2 = ((number-1)/3+1)*((number-1)/3)*3/2   // 计算被3整除的数字之和
+ ((number-1)/5+1)*((number-1)/5)*5/2    // 计算被5整除的数字之和
- ((number-1)/15+1)*((number-1)/15)*15/2;// 计算被 3*5 整除的数字之和


备注:方法二最开始写时,居然忘了要减去被15整除的数字之和。



效率分析



ns为单位执行时间如下:

n

方法一 (ns)

方法二 (ns)

1

44235

1843

2

44235

1844

3

44235

2457

4

44234

1843

平均值

44234.75

1996.75

方法一用时约是方法二的22倍。

多一点思考,多一些效率,终于找到现在公司系统开销大的原因了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: