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

编程入门 行业动态 更新时间:2024-10-27 06:24:41
本文介绍了项目欧拉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

本文发布于:2023-11-29 19:23:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647394.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:倍数   总和   欧拉   项目

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!