项目欧拉1:找到3所有倍数低于1000的总和或5倍数、总和、欧拉、项目

2023-09-11 00:00:59 作者:南辞

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

  

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

     

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

请帮我提高我的code。

 总= 0

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

把总
 
利用matlab中的欧拉法解初值问题.

解决方案

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

 高清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.