gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:25:30 26 4
gpt4 key购买 nike

目前在学习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,函数将永远不会到达它的最后一行,因为 return

提示 3:如果您到达 each block 的末尾,next 是自动的。

提示4:立方之和不需要每次都从头重新计算。您并不是在 build 一座全新的建筑,您只是在下面放置了一个更大的立方体。

所以...

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

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

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

关于Ruby 初学者 - 需要帮助优化此代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40857191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com