问题陈述:
建造一栋将堆起n个立方体的建筑物。底部的立方体的体积为n ^ 3,上方的立方体的体积为(n-1)^ 3,依此类推,直到顶部的立方体的体积为1 ^ 3。
给出建筑物的总体积m。给定m可以找到要构建的多维数据集个数n?
函数findNb的参数(find_nb,find-nb,findNb)将是整数m,并且您必须返回整数n,例如n ^ 3 +(n-1)^ 3 + ... + 1 ^ 3 = m(如果存在),则为-1,如果不存在这样的n。
以下代码在数学上是正确的,可以计算正确的值,但是在通过代码战提交时将失败。该消息表明,如果在其服务器上执行超过12秒,则需要更多优化。谢谢您的帮助。
def find_nb(m):
# your code
n = int(m**(1./3.))
#print (n)
total_volume = 0
for i in range (1,n+1):
#print (i*i*i)
total_volume+= i*i*i
#print (total_volume)
if(total_volume == m):
#print (i)
return i
break
return -1
答案 0 :(得分:0)
You should try to use some maths. Typically, the sum of k^3 for k=1 to n is (n(n+1)/2)^2. So
def find_nb(m):
i=0
while int((i(i+1)/2)**2) < m:
i += 1
if ((i(i+1)/2)^2) == m:
return(i)
return(-1)
This is probably not the best solution, but you should try it, as it enables to avoid a loop.