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-b, findNb, ...) 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.Examples:
findNb(1071225) --> 45findNb(91716553919377) --> -1
題目理解:假底一立方體組成之建築物,最底下立方體體積為n^3;則再往上一層的立方體體積為(n-1)^3,以此類推直到最頂部立方體體積為1^3為止。給定一個建築物總體積m,返還建造此建築物所需的立方體數量n,若找不到此數字n則返還-1。
def find_nb(m):
#先假定n等於1從最上層開始計算總建築物體積
n = 1
building_volume = 0
#持續往下層累加體積,若累計體積超出m代表找不到符合的立方體數量
while building_volume <= m:
building_volume += n**3
#若累積體積洽等於m,此時n則剛好是目標需要的立方體個數
if building_volume == m:
return n
n += 1
return -1