Project Euler 第一题效率分析

时间:2015-10-31 18:25:34   收藏:0   阅读:304

Project Euler:

的环境。

第一题 Multiples of 3 and 5

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.

解决思路

for (int i=0; i<1000; i++) {
    if (i%3==0 || i%5==0)
    sum+=i;
}
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倍。

多一点思考,多一些效率,终于找到现在公司系统开销大的原因了。

原文:http://www.cnblogs.com/willsuna/p/4925846.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!