加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby初学者 – 需要帮助优化此代码

发布时间:2020-12-17 03:42:42 所属栏目:百科 来源:网络整理
导读:目前正在学习 Ruby /编程的过程中,我遇到了这个问题: Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3 ,the cube above will have volume of (n-1)^3 and so on until the top w
目前正在学习 Ruby /编程的过程中,我遇到了这个问题:

Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3,the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.
You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?
The parameter of the function findNb(find_nb,find-nb) will be an integer m and you have to return the integer n such as n^3 + (n-1)^3 + ... + 1^3 = m if such a n exists or -1 if there is no such n*.

这是我试图解决这个问题:

def find_nb(m)
  (1..Float::INFINITY).each do |n|
    if (1..n).inject(0) {|sum,value| sum + value**3} == m
      return p n 
    else
      next
    end
  end
end

这似乎适用于我知道可以工作的输入,例如:

find_nb(4183059834009)
find_nb(135440716410000)
find_nb(40539911473216)

我需要帮助的领域:

>我不知道如果没有n的值满足等式,我会如何理解它,因此输出-1作为输入,如

find_nb(24723578342962)

>非常感谢有关如何使现有代码更好的任何提示.

解决方法

提示1:你不需要进入无穷大:在某个n之后,总和将大于m,并且会越来越远.

提示2:如果找到n,由于返回,函数将永远不会到达最后一行.

提示3:如果到达每个块的末尾,则下一个是自动的.

提示4:每次都不需要从头开始重新计算立方体的总和.你没有建造一座全新的建筑,只是在下面放一个更大的立方体.

所以…

def find_nb(m)
  n = 1
  sum = 1
  while sum < m
    n += 1
    sum += n**3
  end
  return sum == m ? n : -1
end

编辑:这是一个功能版本,但我认为上面的平原仍然更清晰(也可能更快):

def find_nb(m)
  sum = 0
  sizes = 1.upto(Float::INFINITY)
    .lazy
    .map { |n| sum += n ** 3 }
    .take_while { |x| x <= m }
    .to_a
  sizes.last == m ? sizes.length : -1
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读