项目欧拉1:找到3所有倍数低于1000的总和或5 [英] Project Euler 1:Find the sum of all the multiples of 3 or 5 below 1000

查看:158
本文介绍了项目欧拉1:找到3所有倍数低于1000的总和或5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解决数学问题在Ruby从项目欧拉。 这里是我想第一个:

  

如果我们列出的所有自然数   低于10是3或5的倍数,   我们得到3,5,6和9的这些总和   倍数为23。

     

找到3所有倍数的总和   或5千以下。

请帮我提高我的code。

 总= 0

(0 ... 1000)。每个做|我|
  共有+ =,如果我(I%3 == 0 || I%5 == 0)
结束

把总
 

解决方案

更​​快(固定时间)答案:

 高清sum_multiples(多个,到)
    N =(对1)/多
    N *(N + 1)/ 2 *倍数
结束

IRB(主):001:0> sum_multiples(3,10)+ sum_multiples(5,10) -  sum_multiples(15,10)
=> 23
IRB(主):002:0> sum_multiples(3,1000)+ sum_multiples(5,1000) -  sum_multiples(15,1000)
=> 233168
 

为什么这项工作? sum_multiples 作品出,但不包括(它依赖于整数除法)。它首先作品出的倍数被求和数的数目( N ),然后倍数的标准公式1..n的总和= N(N + 1)/ 2按。利用这一点,我们就可以加在一起的数额为3和5的倍数然后,我们决不能忘记,有些数字是的的倍数既的3和5,所以我们减去15(3 * 5的倍数)。

虽然你的答案是绰绰有余快在这个问题上的制约,一个更快的解决方案(它应该在大约1毫秒现代的硬件上运行),如一个我提供将给出一个结果上非常大的数字。

I am trying to solve math problems with Ruby from the Project Euler. Here is the first one I tried:

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.

Please help me to improve my code.

total = 0

(0...1000).each do |i|
  total += i if (i%3 == 0 || i%5 == 0)
end

puts total

解决方案

Much faster (constant time) answer:

def sum_multiples(multiple, to)
    n = (to-1) / multiple
    n * (n+1) / 2 * multiple
end

irb(main):001:0> sum_multiples(3, 10) + sum_multiples(5, 10) - sum_multiples(15, 10)
=> 23
irb(main):002:0> sum_multiples(3, 1000) + sum_multiples(5, 1000) - sum_multiples(15, 1000)
=> 233168

Why does this work? sum_multiples works out the sum of multiples of multiple up to but not including to (it relies on integer division). It first works out the number of number of multiples being summed (n), then multiples the standard formula for the sum of 1..n = n(n+1)/2 by multiple. Using this, we can add together the sums for the multiples of 3 and 5. We must then not forget that some numbers are multiples of both 3 and 5, so we subtract multiples of 15 (3*5).

Although your answer is more than fast enough for the constraints in this problem (it should run in about 1 millisecond on modern hardware), a faster solution such as the one I provide will give a result on very large numbers.

这篇关于项目欧拉1:找到3所有倍数低于1000的总和或5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆